思路
3個線程A,B,C分別打印三個字母稻艰,每個線程循環(huán)10次,首先同步侈净,如果不滿足打印條件尊勿,則調(diào)用wait()函數(shù)一直等待;之后打印字母畜侦,更新state元扔,調(diào)用notifyAll(),進入下一次循環(huán)旋膳。
代碼
package test;
public class PrintABC {
private static final int PRINT_A = 0;
private static final int PRINT_B = 1;
private static final int PRINT_C = 2;
private static class MyThread extends Thread {
int which; // 0:打印A澎语;1:打印B;2:打印C
static volatile int state; // 線程共有验懊,判斷所有的打印狀態(tài)
static final Object t = new Object();
public MyThread(int which) {
this.which = which;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (t) {
while (state % 3 != which) {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(toABC(which)); // 執(zhí)行到這里擅羞,表明滿足條件,打印
state++;
t.notifyAll(); // 調(diào)用notifyAll方法
}
}
}
}
public static void main(String[] args) {
new MyThread(PRINT_A).start();
new MyThread(PRINT_B).start();
new MyThread(PRINT_C).start();
}
private static char toABC(int which) {
return (char) ('A' + which);
}
}