wait和notify机制
public class Test1 {
public static void main(String[] args) {
String s=new String("");
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
报错:
必须在同步方法或同步块中调用wait()/notify()方法
给对象加锁:
public class Test2 {
public static void main(String[] args) {
String s=new String("");
System.out.println("syn上面");
synchronized (s){
System.out.println("syn第一行!");
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("wait下面的代码!");
}
}
}
由于线程没有收到通知,调用wait()方法后,会陷入无限等待中,直到收到通知
原文:https://www.cnblogs.com/crusadesky/p/15036266.html