You are here: Home / Topics / Program to Suspend and Resume the thread using wait() and notify() method in Java Thread

Program to Suspend and Resume the thread using wait() and notify() method in Java Thread

Filed under: Java on 2023-10-16 06:53:47

// Program to Suspend and Resume the thread using
// wait() and notify() method.

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
}

public void run() 
{
 try 
 {
  for(int i = 5; i > 0; i--) 
  {
   System.out.println(name + ": " + i);
   Thread.sleep(200);
   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 ob1 = new NewThread("One");
 NewThread ob2 = new NewThread("Two");
 try 
 {
  Thread.sleep(1000);
  ob1.mysuspend();
  System.out.println("Suspending thread One");
  Thread.sleep(1000);
  ob1.myresume();
  System.out.println("Resuming thread One");
  ob2.mysuspend();
  System.out.println("Suspending thread Two");
  Thread.sleep(1000);
  ob2.myresume();
  System.out.println("Resuming thread Two");
 } 
 catch (InterruptedException e) 
 {
  System.out.println("Main thread Interrupted");
 }
 // wait for threads to finish
 try 
 {
  System.out.println("Waiting for threads to finish.");
  ob1.t.join();
  ob2.t.join();
 } 
 catch (InterruptedException e) 
 {
  System.out.println("Main thread Interrupted");
 }
 System.out.println("Main thread exiting.");
}
}


Output:

New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
One: 10
Two: 10
One: 9
Two: 9
One: 8
Two: 8
One: 7 
Two: 7
One: 6
Two: 6
Suspending thread One
Two: 5
Two: 4
Two: 3
Two: 2
Two: 1
Resuming thread One
Suspending thread Two
One: 5
One: 4
One: 3
One: 2
One: 1
Resuming thread Two
Waiting for threads to finish.
Two exiting.
One exiting.
Main thread exiting.

About Author:
K
Kirti     View Profile
I am from NCR region. Follow one course until sucess.