遇到過一個面試題,按順序打印abc,輸出十次,先說下解題思路,當打印a後,打印a和打印c的程序不能執行,只有打印b的程序可以執行,以此類推,就可以輕鬆解答了。
runnable實現如下:
class SortRunnable implements Runnable{
private String value;
private final Object prev;
private final Object self;
SortRunnable(String value, Object prev, Object self) {
this.value = value;
this.prev = prev;
this.self = self;
}
@Override
public void run() {
int count = 10;
while (count > 0) {
synchronized (prev) {
synchronized (self) {
System.out.print(value);
count--;
self.notify();
}
try {
// 如果這裏不設置超時時間,程序將進入死鎖,不會停止
prev.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
調用方法:
public class Main {
public static void main(String[] args) {
String a = "a";
String b = "b";
String c = "c";
SortRunnable a1 = new SortRunnable("A", c, a);
SortRunnable b1 = new SortRunnable("B", a, b);
SortRunnable c1 = new SortRunnable("C", b, c);
new Thread(a1).start();
new Thread(b1).start();
new Thread(c1).start();
}
}
輸出結果:
ABCABCABCABCABCABCABCABCABCABC
這裏備一個planB:
public class Main {
private static Boolean isThreadA = true;
private static Boolean isThreadB = false;
private static Boolean isThreadC = false;
public static void main(String[] args) {
final Main obj = new Main();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (obj) {
while(!isThreadA) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("A");
isThreadA = false;
isThreadB = true;
isThreadC = false;
obj.notifyAll();
}
}
}).start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (obj) {
while(!isThreadB) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("B");
isThreadA = false;
isThreadB = false;
isThreadC = true;
obj.notifyAll();
}
}
}).start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (obj) {
while(!isThreadC) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("C");
isThreadA = true;
isThreadB = false;
isThreadC = false;
obj.notifyAll();
}
}
}).start();
}
}