notify是唤醒正在等待的资源,wait来让资源等待
Object对象里面有notify和wait两个方法
在使用wait的时候,注意要加上异常处理,try--catch
public class PrintSelf implements Runnable{
private String name;
private Object a;
private Object b;
public PrintSelf(String name,Object a,Object b){
this.name=name;
this.a=a;
this.b=b;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Object a=new Object();
Object b=new Object();
Object c=new Object();
System.out.println("开始:");
PrintSelf pa=new PrintSelf("a",a,b);
PrintSelf pb=new PrintSelf("b",b,c);
PrintSelf pc=new PrintSelf("c",c,a);
new Thread(pa).start();
new Thread(pb).start();
new Thread(pc).start();
}
@Override
public void run() {
// TODO Auto-generated method stub
int count=10;
while(count>0){
synchronized(a){
synchronized(b){
System.out.println(name);
count--;
b.notify();
}
try{
a.wait();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
还有两种方式,阻塞队列和current包实现点击打开链接