有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印ABC十次
package Thread.abc;
public class ABCPrintInOrder {
public static void main(String[] args) {
Object obj = new Object();
PrintA A = new PrintA();
PrintC C = new PrintC(A);
PrintB B = new PrintB(C);
A.setPrintB(B);
A.setPrintC(C);
A.start();
}
}
class PrintA extends Thread {
PrintB B;
PrintC C;
public PrintA(){}
public PrintA(PrintB B){ this.B = B; }
@Override
public synchronized void start() {
super.start();
synchronized (this.B){
try {
//System.out.println("A: B僵尸");
this.B.wait();
} catch (InterruptedException e) {}
}
//System.out.println("A: B准备开始执行");
B.start();
}
@Override
public void run() {
while(true){
print();
try {
Thread.sleep(300);
} catch (InterruptedException e) {}
}
}
public void print(){
System.out.println("A");
synchronized (this.B){
//System.out.println("A: 复活B");
this.B.notifyAll();
}
synchronized (this.C) {
try {
//System.out.println("A: 僵尸C");
this.C.wait();
} catch (InterruptedException e) { }
}
synchronized (this) {
try {
//System.out.println("A: 僵尸A");
this.wait();
} catch (InterruptedException e) { }
}
}
public void setPrintB(PrintB B){ this.B = B; }
public void setPrintC(PrintC C){ this.C = C; }
}
class PrintB extends Thread {
PrintC C;
public PrintB(PrintC C){ this.C = C; }
@Override
public synchronized void start() {
super.start();
synchronized (this.C){
try {
//System.out.println("B: C僵尸");
this.C.wait();
} catch (InterruptedException e) {}
}
//System.out.println("B: C准备开始执行");
C.start();
}
@Override
public void run() {
while(true){
print();
try {
Thread.sleep(400);
} catch (InterruptedException e) { }
}
}
public void print(){
System.out.println("B");
synchronized (this.C){
this.C.notifyAll();
}
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) { }
}
}
}
class PrintC extends Thread {
PrintA A;
public PrintC(PrintA A){
this.A = A;
}
@Override
public void run() {
while(true){
print();
try {
Thread.sleep(500);
} catch (InterruptedException e) { }
}
}
public void print(){
System.out.println("C");
synchronized (this.A){
//System.out.println("--------------");
this.A.notifyAll();
}
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) { }
}
}
}