I am working on an application and need to be able to pause the main thread mid-processing. My idea was to have three threads: main, a thread listening for input (either STOP or GO commands) and then another thread to cause the main to stop:
public static boolean stopped = false;
public static void main (String[] args){
Thread main = Thread.currentThread();
Runnable t1 = new Runnable() {
public void run() {
while(true){
Scanner s = new Scanner(System.in);
// wait for command
String in = s.nextLine();
if(in.equals("STOP")){
synchronized(main){
stopped = true;
//create new thread to make main wait
Runnable t2 = new Runnable() {
public void run(){
synchronized(main){
while(stopped){
main.wait();
}
}
}
};
Thread th2 = new Thread(t2);
th2.start();
}
}
if (in.equals("GO")){
synchronized(main){
stopped = false;
main.notifyAll();
}
}
}
}
};
Thread th1 = new Thread(t1);
th1.start();
while(true){
synchronized(main){
// Do lots of stuff that needs to pause when user enters STOP
System.out.println("Main is running");
Thread.sleep(5000);
}
}
}
}
Currently main continues through its loop even after the STOP command is given. Is there a way to lock main until another thread releases it without having to do the wait()
in main?