package Thread; class Number implements Runnable{ private String name; private Object prev; private Object self; private int count; public Number(String name,Object prev,Object self,int count){ this.name=name; this.prev=prev; this.self=self; this.count=count; } @Override public void run() { while(count<=75){ synchronized (prev){ synchronized (self){ for (int i=0;i<5;i++){ count=count+1; if(count>75)break; System.out.println(name+": "+count); } count=count+10; //System.out.println("释放自身锁,并唤醒在等待该锁的线程"); self.notify();//释放自身锁,并唤醒在等待该锁的线程 } //System.out.println("释放自身锁成功"); try { //System.out.println("等待前一个锁"); prev.wait();//等待前一个锁 } catch (InterruptedException e) { e.printStackTrace(); } } //System.out.println("两个锁全部释放,重新进入新的循环,但是由于有prev.wait()所以该线程等待获取prev的锁"); } } } public class Main { public static void main(String[] args) throws InterruptedException { Object a=new Object(); Object b=new Object(); Object c=new Object(); Number A=new Number("线程1",c,a,0); Number B=new Number("线程2",a,b,5); Number C=new Number("线程3",b,c,10); new Thread(A).start(); Thread.sleep(100); new Thread(B).start(); Thread.sleep(100); new Thread(C).start(); Thread.sleep(100); } }
原文:https://www.cnblogs.com/ls1783047205/p/9751130.html