Suspending, resuming, and stopping threads in Java

Java's threads allow for concurrent processing of multiple requests. Java includes functionality to pause, resume, and terminate running threads. Using these functions, you can manage thread execution and guarantee that it proceeds normally.

So, in this post, I'll go over how to suspend, resume, and terminate threads in the Java programming language. However, if you are unfamiliar with multithreading in Java, it is recommended that you learn it first and then proceed to understand how thread suspending, resuming, and stopping work.

Suspending Threads in Java

In Java, a thread can be suspended by using the wait() method on an object. This method suspends thread execution until it is notified by another thread using the notify() method. As an example:

Object lock = new Object();
Thread myThread = new Thread(() -> {
    synchronized(lock) {
        try {
            lock.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
});
myThread.start();       // start thread
synchronized(lock) {
    lock.notify();      // resume thread
}

Resuming Threads in Java

An interrupted thread's execution can be picked back up by notifying the waiting thread using the notify() method. As an example:

Object lock = new Object();
Thread myThread = new Thread(() -> {
    synchronized(lock) {
        try {
            lock.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
});
myThread.start();         // start thread
myThread.interrupt();     // interrupt thread
synchronized(lock) {
    lock.notify();        // resume thread
}

Stopping Threads in Java

To halt a running thread, use a boolean flag to signal the thread to stop gracefully. Consider the following code fragment as an example:

class MyThread extends Thread {
    private volatile boolean running = true;
    
    public void stopThread() {
        running = false;
    }
    
    public void run() {
        while(running) {
            // do some work
        }
    }
}

MyThread myThread = new MyThread();
myThread.start();          // start thread
myThread.stopThread();     // stop thread

Suspending Resuming, and Stopping Threads Example Program in Java

Consider the following program as an example demonstrating the suspending, resuming, and stopping of threads in the Java programming language:

Java Code
class MyThread implements Runnable {
    Thread td;
    volatile boolean suspended;
    volatile boolean stopped;

    MyThread(String name) {
        td = new Thread(this, name);
        suspended = false;
        stopped = false;
        td.start();
    }

    public void run() {
        System.out.println(td.getName() + " starting.");
        try {
            for (int i = 1; i < 1000 && !stopped; i++) {
                System.out.print(i + " ");
                if (i % 10 == 0) {
                    System.out.println();
                    Thread.sleep(250);
                }
                synchronized (this) {
                    while (suspended) {
                        wait();
                    }
                }
            }
        } catch (InterruptedException e) {
            System.out.println(td.getName() + " interrupted.");
        }
        System.out.println(td.getName() + " exiting.");
    }

    synchronized void stop() {
        stopped = true;
        suspended = false;
        notify();
    }

    synchronized void suspendThread() {
        suspended = true;
    }

    synchronized void resumeThread() {
        suspended = false;
        notify();
    }
}

public class ThreadExample {
    public static void main(String args[]) throws InterruptedException {
        MyThread thread1 = new MyThread("Thread 1");
        MyThread thread2 = new MyThread("Thread 2");

        Thread.sleep(1000);

        thread1.suspendThread();
        System.out.println("\nSuspending " + thread1.td.getName());
        Thread.sleep(1000);

        thread1.resumeThread();
        System.out.println("\nResuming " + thread1.td.getName());
        Thread.sleep(1000);

        thread2.suspendThread();
        System.out.println("\nSuspending " + thread2.td.getName());
        Thread.sleep(1000);

        thread2.resumeThread();
        System.out.println("\nResuming " + thread2.td.getName());
        Thread.sleep(1000);

        thread1.stop();
        System.out.println("\nStopping " + thread1.td.getName());
        Thread.sleep(1000);

        thread2.stop();
        System.out.println("\nStopping " + thread2.td.getName());
    }
}
Output
Thread 1 starting.
Thread 2 starting.
1 2 3 4 1 2 3 5 6 7 8 9 10 4 
5 6 7 8 9 10 
11 11 12 13 14 15 16 17 18 19 20 
12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 
21 22 23 24 25 26 27 28 29 30 
31 32 33 34 35 36 37 38 39 40 
31 32 33 34 35 36 37 38 39 40 

Suspending Thread 1
41 42 43 44 45 46 47 48 49 50 
51 52 53 54 55 56 57 58 59 60 
61 62 63 64 65 66 67 68 69 70 
71 72 73 74 75 76 77 78 79 80 
41 42 43 44 45 46 47 48 49 50 

Resuming Thread 1
81 82 83 84 85 86 87 88 89 90 
51 52 53 54 55 56 57 58 59 60 
91 92 93 94 95 96 97 98 99 100 
61 62 63 64 65 66 67 68 69 70 
101 102 103 104 105 106 107 108 109 110 
71 72 73 74 75 76 77 78 79 80 
111 112 113 114 115 116 117 118 119 120 

Suspending Thread 2
81 82 83 84 85 86 87 88 89 90 
91 92 93 94 95 96 97 98 99 100 
101 102 103 104 105 106 107 108 109 110 
111 112 113 114 115 116 117 118 119 120 
121 122 123 124 125 126 
Resuming Thread 2
127 128 129 130 
121 122 123 124 125 126 127 128 129 130 
131 132 133 134 135 136 137 138 139 140 
131 132 133 134 135 136 137 138 139 140 
141 142 143 144 145 146 147 148 149 150 
141 142 143 144 145 146 147 148 149 150 
151 152 153 154 155 156 157 158 159 160 
151 152 153 154 155 156 157 158 159 160 

Stopping Thread 1
161 162 163 164 165 166 167 168 169 170 
Thread 1 exiting.
171 172 173 174 175 176 177 178 179 180 
181 182 183 184 185 186 187 188 189 190 
191 192 193 194 195 196 197 198 199 200 

Stopping Thread 2
Thread 2 exiting.

This program creates a class called MyThread that adheres to the interface known as Runnable. There are three ways to stop, suspend, and resume a thread in the MyThread class.

The MyThread class's run method defines the thread's behavior, which is to print numbers from 1 to 999 with a delay of 250 milliseconds after every ten numbers, until the stopped flag becomes true. If the suspended flag is set, the thread waits by invoking the object's wait method.

The ThreadExample class instantiates two instances of the MyThread class and calls the suspendThread, resumeThread, and stop methods on them after a second interval. The suspendThread method sets the suspended flag to true, causing the thread to be suspended by calling wait on the object. To wake up the waiting thread, the resumeThread method sets the suspended flag to false and calls notify on the object. The stopped flag is set to true by the stop method, which terminates the thread.

Java Online Test


« Previous Tutorial CodesCracker.com »


Liked this post? Share it!