忽然想到之前的一個面試題:三個線程順序打印 ABC蛛株,該怎么實現(xiàn)蜘犁?于是又自己動手寫了一遍翰苫。
public class ThreadABC {
private static boolean printA = true;
private static boolean printB = false;
private static boolean printC = false;
public static void main(String[] args) {
final ThreadABC threadABC = new ThreadABC();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (threadABC) {
while (true) {
while (!printA) {
try {
threadABC.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
printA = false;
printB = true;
printC = false;
threadABC.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (threadABC) {
while (true) {
while (!printB) {
try {
threadABC.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
printA = false;
printB = false;
printC = true;
threadABC.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (threadABC) {
while (true) {
while (!printC) {
try {
threadABC.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C");
printA = true;
printB = false;
printC = false;
threadABC.notifyAll();
}
}
}
}).start();
}
}