Suspending and Resuming Thread

Every thread may perform different tasks. Sometimes, it becomes necessay to suspend the execution of a thread for a period of time. This can be done by using suspend() method of the class. We can restart the thread by using resume() method.stop() is used to stop the thread, it cannot be restarted again.

 

import java.io.*;

class Suspendthread

{

public static void main(String aa[])

{

Thread thrd1=new Thread();

Thread thrd2=new Thread();

try

{

Thread.sleep(1000);

System.out.println("SUSPENDING FIRST THREAD");

thrd1.suspend();

Thread.sleep(1000);

System.out.println("RESUMING FIRST THREAD");

thrd1.resume();

System.out.println("SUSPENDING SECOND THREAD");

thrd2.suspend();

Thread.sleep(1000);

System.out.println("RESUMING SECOND THREAD");

thrd2.resume();

}

catch(InterruptedException iee)

{

System.out.println("INTERUPTED MAIN THREAD");

}

try

{

System.out.println("Applying joins");

thrd1.join();

thrd2.join();

}

catch(InterruptedException ie)

{

System.out.println("INTERRUPTED MAIN THREAD");

}

System.out.println("EXITING MAIN THREAD");

}

}

Suspending and Resuming Thread in Java

Explanation….

Inside the main() a new instance of thread is created.

The inside the try block, the first thread is put to sleep for 1000 miliseconds, after which the System.out.println statement prints the statement “SUSPENDING FIRST THREAD”.

Then, the current execution of the first thread is suspended using the method suspend() method.

The thread is again put to sleep, after which the System.out.println statement prints the statement “RESUMING FIRST THREAD”.

Now the first thread that was suspended is resumed with the method resume().

Then, the System. out. println statement prints the statement “SUSPENDING SECOND THREAD”.

Now the current execution of the second thread is suspended using method suspend().

The second thread is put to sleep, after which the System.out.println statement prints the statement ”RESUMING SECOND THREAD

The second thread that was suspended is resumed using resume().

The catch method prints statement “MAIN THREAD INTERRUPTED”(error) if it encounters an error.

Then, the two threads are joined using join() before which a System.out.println prints the statement “Applying joins”(joins two threads).

If an error occurs while joining the threads, the catch throws an exception with the statement“INTERRUPTED MAIN THREAD”.

Finally the System.out.println statement prints a message “EXITING MAIN THREAD

About Us

Rekha SetiaRekha Setia is a passionate blogger of Extra Computer Notes. if you have any ideas or any request me @