写这篇文章让我想起了"茴香豆的茴字有几种写法"。前面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();
}
}