You can use a flag to control if to stop a thread.
If the flag is set, the thread should stop executing.
The following code simulates the stop(), suspend(), and resume() methods of the Thread class in your thread.
public class Main { public static void main(String[] args) throws Exception { MyThread t = new MyThread(); t.start();// w ww . ja v a 2 s . c o m Thread.sleep(2000);// Sleep for 2 seconds t.suspendThread(); // Sleep for 2 seconds Thread.sleep(2000); // Resume the thread t.resumeThread(); Thread.sleep(2000); t.stopThread(); } } class MyThread extends Thread { private volatile boolean keepRunning = true; private boolean suspended = false; public synchronized void stopThread() { this.keepRunning = false; this.notify(); } public synchronized void suspendThread() { this.suspended = true; } public synchronized void resumeThread() { this.suspended = false; this.notify(); } public void run() { System.out.println("Thread started..."); while (keepRunning) { try { System.out.println("Going to sleep..."); Thread.sleep(1000); synchronized (this) { while (suspended) { System.out.println("Suspended..."); this.wait(); System.out.println("Resumed..."); } } } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Thread stopped..."); } }
The suspended instance variable is not declared volatile.
It is not necessary to declare it volatile because it is always accessed inside a synchronized method/block.
The following code in the run() method is used to implement the suspend and resume features:
synchronized (this) { while (suspended) { System.out.println("Suspended..."); this.wait(); System.out.println("Resumed..."); } }
When the suspended instance variable is set to true, the thread calls the wait() method on itself to wait.