I can suspend the thread with user input in console,but can’t resume it again with user input.
I want to resume the thread when user gives input “n”. Again it will start with prev state
please help folks.
Thanks.
import java.io.Console;
import java.util.Scanner;
class NewThread implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
// String username = scanner.nextLine();
try {
for(int i = 5000; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
//String username = scanner.nextLine();
// if(username.equals("y"))
// {
// mysuspend();
// }
synchronized(this) {
while(suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
notify();
}
}
class SuspendResume {
public static void main(String args[]) {
NewThread ob2 = new NewThread("One");
// System.out.println(username);
try { Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
if(username.equals("y"))
{
Thread.interrupted();
// Thread.sleep(10000);
ob2.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(10000);
// ob2.myresume();
System.out.println("Resuming thread One");
}
if(username.equals("n"))
{
ob2.myresume();
}
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Your control flow is wrong.
You are reading input only once. If it is equal to
yyou are suspending the thread, but then you never go into the if statement that tests fornto resume the thread. I would do it like this:If the user enters “y” the thread will be suspended. If they enter “n” it will be resumed and if they enter “q” you will just break the loop and wait for the thread to finish.