這是這裏上午03點半,我想睡覺了。 這是我想出了:
class TurnHolder {
private volatile int currentTurn;
public void setNextTurn() {
this.currentTurn = currentTurn^1;
}
public int getCurrentTurn() {
return currentTurn;
}
}
class Printer implements Runnable {
private String toPrint;
private TurnHolder sharedResource;
private int turn;
Printer(String toPrint, TurnHolder sharedResource, int turn) {
this.toPrint = toPrint;
this.sharedResource = sharedResource;
this.turn = turn;
}
@Override
public void run() {
while (true) {
synchronized (sharedResource) {
if (sharedResource.getCurrentTurn() != turn)
try {
sharedResource.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(toPrint);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sharedResource.setNextTurn();
sharedResource.notifyAll();
}
}
}
一種方式來運行它:
TurnHolder sharedResource = new TurnHolder();
Printer printerA = new Printer("a", sharedResource, 0);
Printer printerB = new Printer("b", sharedResource, 1);
new Thread(printerA).start();
new Thread(printerB).start();
這樣你sharedResource
將保持轉彎的內存和同步上它可以讓你做什麼你必須處理這個轉彎,然後你可以轉彎。 Thread.sleep
只是讓您以不錯的速度看到打印內容。 的System.out.println(toPrint);
是如何提高代碼的printThreadOutput();
P.S:建議都歡迎。
'while(turn!= turn)'? –
'synchronized'應該解析非det –
你的代碼包含縮進的混合標籤和空格 - 這是一個壞主意。您應該確保始終使用製表符或空格。 – thejh