3個線程分別調(diào)用3個方法辜御,用3個標(biāo)志位控制順序鸭你。
用AtomicInteger記錄次數(shù)。
A線程打印的條件是isCDone為true擒权,isCDone初始狀態(tài)為true袱巨。
B線程打印的條件是isADone為true,如果為false時碳抄,調(diào)用wait()愉老,線程會等待。
C線程打印的條件是isBDone為true剖效,如果為false時嫉入,調(diào)用wait()焰盗,線程會等待。
A線程執(zhí)行結(jié)束會通知其他線程咒林,此時BC都被喚醒熬拒,競爭鎖,如果C搶到鎖垫竞,因為isBDone為false繼續(xù)等待并通知其他線程澎粟,如果B搶到因為isADone為true,打印欢瞪。
每個線程的方法打印后都會通知其他線程捌议,并且把自己打印的條件改為false,避免多次執(zhí)行引有。例如A線程打印的條件是isCDone為true瓣颅,那么A線程打印后要把isCDone改為false。
public class PrintABC {
public static void main(String[] args) {
PrintObject printObject = new PrintObject(100);
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
printObject.printA();
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
printObject.printB();
}
});
Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
printObject.printC();
}
});
threadC.start();
threadB.start();
threadA.start();
}
static class PrintObject {
int n = 10;
AtomicInteger count = new AtomicInteger(0);
PrintObject() {
}
PrintObject(int n) {
this.n = n;
}
boolean isADone = false;
boolean isBDone = false;
boolean isCDone = true;
public void printA() {
while (count.get() < n) {
synchronized (this) {
while (!isCDone) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
isADone = true;
isCDone = false;
count.incrementAndGet();
this.notifyAll();
}
}
}
public void printB() {
while (count.get() < n) {
synchronized (this) {
while (!isADone) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
isBDone = true;
isADone = false;
this.notifyAll();
}
}
}
public void printC() {
while (count.get() < n) {
synchronized (this) {
while (!isBDone) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C");
isCDone = true;
this.notifyAll();
isBDone = false;
System.out.println("count:: " + count.get());
}
}
}
}
}