Suspending, Resuming, and Stopping Threads in java

In Java, managing the lifecycle of threads involves several actions, including starting, suspending, resuming, and stopping threads. These operations can be performed using methods provided by the Thread class and by using synchronization mechanisms. Below are explanations and examples for suspending, resuming, and stopping threads in Java:

Suspending a Thread:

Suspending a thread means temporarily halting its execution. In Java, the suspend() method is used for this purpose. However, note that this method is deprecated due to potential deadlock issues. It’s recommended to use other mechanisms, such as wait() and notify(), or higher-level concurrency utilities.

Example (Deprecated suspend() method):

class MyThread extends Thread {
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(Thread.currentThread().getId() + " Value " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ThreadExample {
    public static void main(String args[]) {
        MyThread t1 = new MyThread();
        t1.start();

        try {
            Thread.sleep(2000); // Sleep for 2 seconds
            t1.suspend(); // Deprecated: Suspend the thread
            System.out.println("Thread suspended");
            Thread.sleep(2000); // Sleep for 2 seconds
            t1.resume(); // Deprecated: Resume the thread
            System.out.println("Thread resumed");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Resuming a Thread:

Resuming a thread means allowing it to continue execution after it has been suspended. The resume() method (deprecated) can be used to resume a suspended thread. However, for modern applications, it’s recommended to use alternative approaches.

Example (Deprecated resume() method):

// Same example as above, showing the use of resume() (deprecated).

Stopping a Thread:

Stopping a thread means ending its execution. The stop() method is used to stop a thread. Similar to suspend(), this method is deprecated due to its unsafe nature. It’s recommended to use a shared variable or a flag to signal the thread to stop gracefully.

Example (Deprecated stop() method):

class MyThread extends Thread {
    private volatile boolean running = true;

    public void run() {
        while (running) {
            System.out.println(Thread.currentThread().getId() + " Running");
        }
    }

    public void stopThread() {
        running = false;
    }
}

public class ThreadExample {
    public static void main(String args[]) {
        MyThread t1 = new MyThread();
        t1.start();

        try {
            Thread.sleep(5000); // Sleep for 5 seconds
            t1.stopThread(); // Stop the thread
            System.out.println("Thread stopped");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In the above example, the stopThread() method sets the running flag to false, signaling the thread to stop gracefully.

Note:

  • Deprecated methods like suspend() and resume() are discouraged due to their potential to cause deadlock situations. Modern Java applications use safer alternatives, such as the use of shared variables and proper synchronization mechanisms, to control thread execution.
  • The examples provided demonstrate the use of deprecated methods for educational purposes. In a real-world scenario, it’s recommended to use more modern and safe approaches for thread management.

Sometimes, suspending execution of a thread is useful. For example, a separate thread can be used to display the time of day. If the user doesn’t want a clock, then its thread can be suspended. Whatever the case, suspending a thread is a simple matter. Once suspended, restarting the thread is also a simple matter

final void suspend( )
final void resume( )

Example of Using suspend() and resume()

class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.t.suspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.t.resume();
System.out.println("Resuming thread One");
ob2.t.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.t.resume();
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]
One: 15
New thread: Thread[Two,5,main]
Two: 15
One: 14
Two: 14
One: 13
Two: 13
One: 12
Two: 12
One: 11
Two: 11
Suspending thread One
Two: 10
Two: 9
Two: 8

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

Leave a Comment