频道栏目
首页 > 资讯 > 其他 > 正文

关于线程交替打印奇偶数的实例讲解

18-07-30        来源:[db:作者]  
收藏   我要投稿

关于线程交替打印奇偶数的实例讲解

在做这个代码之前,其实碰到了一些问题,不过说到底还是基础不行,总结出来就是 切不要以Integer等作为锁的对象,也就是
被锁住的引用 所指向的对象一定不能变,用integer极其容易引起所指向对象的改变 如 i = i+1;等等 切记 切记 。否则会报错哦,(非法对象监视器异常)

例如 : 有个Integer i对象
 synchronized (i) {
  i =i+1;
 i.wait(); //注意这里 i所指向的对象改变, 线程并没有获取到 i重新指 向对象的锁,故会报错 )
}



wait(),notity(),notityAll()的具体使用方法 参考本篇文章  https://yq.aliyun.com/articles/1419 

package com.test;

import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadTest {
 public volatile static boolean flag1 = true;
 public volatile static AtomicInteger i = new AtomicInteger(0); //这里为了方便直接使用原子类,
  //其实可以创建一个对象
 //该对象有一个int属性即可 ;
 public static void main(String[] args) {
  Thread thread1 = new Thread1();
Thread thread2 = new Thread2();
  thread1.start();
thread2.start();
  

 }

 static class Thread1 extends Thread {

  @Override
  public void run() {
while (i.get() < 10) {
 synchronized (i) {
  try {
while (i.get()
  % 2 == 0) {
 System.out.println(Thread.currentThread() + ":" + i);
 i.incrementAndGet();
 //System.out.println("2222");

 i.notify();  //唤醒对象等待队列中的一个等待的线程


}
while (i.get() % 2 != 0) {
 i.wait();  //奇数 , wait暂时释放锁 ,成为阻塞状态
}



  } catch (InterruptedException e) { //这里抓捕异常 一般不会进入这里

e.printStackTrace();
  }
 }
}
flag1 = false;

  }

  @Override
  public String toString() {
return "Thread-1";
  }
 }

 static class Thread2 extends Thread {
  @Override
  public void run() {
while (i.get() < 10){
 synchronized (i) {
  try {
while (i.get() % 2 != 0) {
// System.out.println("第二个");
 System.out.println(Thread.currentThread() + ":" + i);
 i.incrementAndGet();
 i.notify(); //唤醒对象等待队列中的一个等待的线程


}

if(i.get()%2==0){
 i.wait(); //偶数 , wait暂时释放锁 ,成为阻塞状态
}

  } catch (InterruptedException e1) {
  // System.out.println("第二个线程堵死");
e1.printStackTrace();
  }


 }

  }
 }

 @Override
 public String toString() {
  return "Thread-2";
 }
}


}

最后还有一点值得注意的是这里会造成一个线程一直处于阻塞状态,造成原因是,当一个线程满足条件后退出,造成阻塞的线程会一直没有人唤醒。 
相关TAG标签
上一篇:swift4 tableViewCell结合Kingfisher 、SnapKit的使用分析
下一篇:写项目中的数据缓存时gson to json遇到的类型转换异常问题的解决办法
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站