/*功能:三个线程,一个打印A,一个打印B,一个打印C,主函数实现循环打印ABCABCABCABC... 共打印10次ABC*/
public class ThreadABC {
public static void main(String[] args) {
Print p = new Print();
/*打印A的进程*/
new Thread(new Runnable() {
public void run() {
for(int i = 0;i <10;++i){//我设置的i打印10次啊
p.print_A();
/*为什么只打印 5 次???!!!*/
/*加上下面这行代码,就能正常打印10次,why???*/
//try{Thread.sleep();}catch(Exception e){;}
}
}
}).start();
/*启动打印B的线程*/
new Thread(new Runnable() {
public void run() {
while(true)
p.print_B();
}
}).start();
/*启动打印C的线程*/
new Thread(new Runnable() {
public void run() {
while(true)
p.print_C();
}
}).start();
}
}
/**/
class Print {
/*flag用来同步*/
private int flag = 1;
/*打印 A */
synchronized void print_A() {
if(flag == 1) {
System.out.print("A");
flag = 2;
try {this.notifyAll();}catch(Exception e) {e.printStackTrace();}
}
else {
try {this.wait();}catch(Exception e) {e.printStackTrace();}
}
}
/*打印B*/
synchronized void print_B() {
if(flag == 2) {
System.out.print("B");
flag = 3;
try {this.notifyAll();}catch(Exception e) {e.printStackTrace();}
}
else {
try {this.wait();}catch(Exception e) {e.printStackTrace();}
}
}
/*打印C*/
synchronized void print_C() {
if(flag == 3) {
System.out.println("C");
flag = 1;
try {this.notifyAll();}catch(Exception e) {e.printStackTrace();}
}
else {
try {this.wait();}catch(Exception e) {e.printStackTrace();}
}
}
}