publicclassT1{publicstaticvoidmain(String[] args){newT1().fun();}privatevoidfun(){try{Object lock =newObject();Thread thread1 =newThread(()->{try{synchronized(lock){for(int i =0; i <10; i++){System.out.println("A");
lock.notify();
lock.wait();}}}catch(Exception e){
e.printStackTrace();}});Thread thread2 =newThread(()->{try{synchronized(lock){for(int i =0; i <10; i++){
lock.wait();System.out.println("B");
lock.notify();}}}catch(Exception e){
e.printStackTrace();}});
thread2.start();Thread.sleep(100);
thread1.start();}catch(Exception e){
e.printStackTrace();}}}
方式二
packagelook.LookUse;publicclassT2{staticThread ta, tb;publicstaticvoidmain(String[] args){int num =10;Thread lock =Thread.currentThread();
ta =newThread(()->{for(int i =0; i < num; i++){try{while(tb.getState()!=Thread.State.WAITING){}synchronized(lock){System.out.println("A"+ i);
lock.notify();if(i != num -1)
lock.wait();}}catch(InterruptedException e){
e.printStackTrace();}}});
tb =newThread(()->{for(int i =0; i < num; i++){try{synchronized(lock){
lock.notify();
lock.wait();System.out.println("B"+ i);}}catch(InterruptedException e){
e.printStackTrace();}}});
ta.start();
tb.start();}}