线程通信
wait(); notify(); / notifyAll();
1. wait();
一旦执行此方法,当前线程进入阻塞状态,并释放同步监视器(锁)。
2.notify();
一旦执行该方法,就会唤醒wait的一个线程,如果有多个线程,就会唤醒优先级高的线程。
3.notifyAll();
一旦执行此方法,就会唤醒所有的wait的线程。
public class Demo003 extends Thread{
private int sum=1;
public void run(){
while(true){
synchronized(this){
notifyAll();
if (sum<=100){
System.out.println(Thread.currentThread().getName()+sum);
sum++;
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
else {
break;
}
}
}
}
}
class A {
public static void main(String[] args) {
Demo003 demo003 = new Demo003();
Thread thread2= new Thread(demo003);
Thread thread1 = new Thread(demo003);
thread1.setName(“1-”);
thread2.setName(“2-”);
thread2.start();
thread1.start();
}
}
再锁的位置不使用与wait相同的对象的时候会报错
public class Demo003 extends Thread{
private int sum=1;
public void run(){
while(true){
synchronized(Demo003.class){//用当前类做锁
notifyAll();//demo003调用的 notifyAll();
if (sum<=100){
System.out.println(Thread.currentThread().getName()+sum);
sum++;
try {
wait();//demo003调用的 wait()
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
else {
break;
}
}
}
}
}
class A {
public static void main(String[] args) {
Demo003 demo003 = new Demo003();
Thread thread2= new Thread(demo003);
Thread thread1 = new Thread(demo003);
thread1.setName(“1-”);
thread2.setName(“2-”);
thread2.start();
thread1.start();
}
}
锁和调用notify与调用wait的对象必须一致
public class Demo003 extends Thread{
private int sum=1;
public void run(){
while(true){
synchronized(Demo003.class){//使用Demo003.class做锁
Demo003.class.notifyAll();Demo003.class做调用notify对象
if (sum<=100){
System.out.println(Thread.currentThread().getName()+sum);
sum++;
try {
Demo003.class.wait();Demo003.class做调用wait对象
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
else {
break;
}
}
}
}
}
class A {
public static void main(String[] args) {
Demo003 demo003 = new Demo003();
Thread thread2= new Thread(demo003);
Thread thread1 = new Thread(demo003);
thread1.setName(“1-”);
thread2.setName(“2-”);
thread2.start();
thread1.start();
}
}