I want to pause and resume a thread by pressing a key. The idea is that the thread generates numbers which are send through a pipe to another thread and the user can pause and resume the thread by pressing the key 'p'. What I have at the moment is this: The thread waits until I press any key and the random number is displayed on screen (output is another thread), then the thread waits until I press another key... but if I press 'p' the thread stops and I cannot get it to resume.
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();
}
}