线程间的通信其实是非常复杂的,这里是一个经典的线程加锁通信的问题。A, B, C三个打印机,每个打印机是一个线程,现在要求写一个程序,让A,B,C轮流打印自己的名字,每个打四次。
public class Printer extends Thread {
private String msg;
private Printer next;
public Printer(String msg) {
this.msg = msg;
}
@Override
public void run() {
for (int i = 1; i < 5; i++) {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第" + i + "次:" + this.msg);
synchronized (this.next) {
this.next.notify();
}
}
}
}
public static void main(String[] args) {
Printer A = new Printer("A");
Printer B = new Printer("B");
Printer C = new Printer("C");
A.next = B;
B.next = C;
C.next = A;
A.start();
B.start();
C.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (A) {
A.notify();
}
}
}