线程通信---wait notify

/**
* 线程通信
*
* @Author: ITYW
* @Create 2020 - 07 - 29 - 9:43
*/
public class Thread_wait_notify_notifyAll {

public static void main(String[] args) {
Number number = new Number();
Thread t1 = new Thread(number);
Thread t2 = new Thread(number);

t1.setName("线程1");
t2.setName("线程2");

t1.start();
t2.start();
}
}
class Number implements Runnable{
private int number = 1;
private Object obj = new Object();
public void run() {

while(true){

synchronized (obj) {

obj.notify();

if(number <= 100){

try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(Thread.currentThread().getName() + ":" + number);
number++;

try {
//使得调用如下wait()方法的线程进入阻塞状态
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

}else{
break;
}
}

}

}
}


posted @ 2020-10-26 19:54  ITYW  阅读(97)  评论(0编辑  收藏  举报