有三个线程ID分别是A、B、C,用多线编程实现在屏幕上循环打印10次ABCABC.(精简版)
?? ? ?写这篇文章让我想起了"茴香豆的茴字有几种写法"。前面http://lilywangcn.iteye.com/blog/793898写了一种解决方法,下面的思想和前面一样,只是结构上简化了一些。
public class Main {private static Object monitor=new Object();private static int flag=1;public static void main(String[] args){new Thread(){public void run(){for(int i=0;i<10;i++){synchronized(monitor){while(flag!=1){try{monitor.wait();}catch(InterruptedException e){}}}try{System.out.print("A");}finally{synchronized(monitor){flag=2;monitor.notifyAll();}}}}}.start();new Thread(){public void run(){for(int i=0;i<10;i++){synchronized(monitor){while(flag!=2){try{monitor.wait();}catch(InterruptedException e){}}}try{System.out.print("B");}finally{synchronized(monitor){flag=3;monitor.notifyAll();}}}}}.start();new Thread(){public void run(){for(int i=0;i<10;i++){synchronized(monitor){while(flag!=3){try{monitor.wait();}catch(InterruptedException e){}}}try{System.out.print("C");}finally{synchronized(monitor){flag=1;monitor.notifyAll();}}}}}.start();}}?