我想通過按一個鍵暫停和恢復線程。這個想法是線程生成的數字通過管道發送到另一個線程,用戶可以通過按'p'鍵暫停和恢復線程。我現在所擁有的是:線程等待,直到我按任意鍵,隨機數字顯示在屏幕上(輸出是另一個線程),然後線程等待,直到我按另一個鍵......但如果按'p線程停止,我無法恢復。通過按鍵暫停和恢復線程
import java.io.IOException;
import java.util.Random;
import java.io.PipedOutputStream;
import java.util.Scanner;
public class Producer extends Thread {
private static final int MIN = 0;
private static final int MAX = 60;
private volatile boolean pause;
private PipedOutputStream output = new PipedOutputStream();
public Producer(PipedOutputStream output) {
this.output = output;
}
@Override
public void run() {
Random rand = new Random();
Scanner reader = new Scanner(System.in);
int random;
String key = "p";
String keyPressed;
try {
while (true) {
keyPressed = reader.next();
if (keyPressed.equalsIgnoreCase(key)) {
pauseThread();
} else {
random = rand.nextInt(MAX - MIN + 1);
output.write((int) random);
output.flush();
Thread.sleep(1000);
}
if (pause = true && keyPressed.equalsIgnoreCase(key)) {
resumeThread();
}
}
output.close();
} catch (InterruptedException ex) {
interrupt();
} catch (IOException ex) {
System.out.println("Could not write to pipe.");
}
}
public synchronized void pauseThread() throws InterruptedException {
pause = true;
while (pause)
wait();
}
public synchronized void resumeThread() throws InterruptedException {
while (pause) {
pause = false;
}
notify();
}
}
好的。什麼是問題? – Jobin
你不應該這樣做。將一個BlockingQueue傳遞給你的線程,並通過它來推動它的所有數字。然後,您可以停止從隊列中讀取以暫停過程。 – OldCurmudgeon
另外 - 你可以嘗試http://stackoverflow.com/a/10669623/823393 – OldCurmudgeon