Stopping the threads

Starting a thread is very easy in java, after you create it you need to call the method start(), for example:

Thread myThread = new Thread(new MyRunnable());
myThread.start();

where MyRunnable is a class implementing the Runnable interface overidden the method run().

The creation of a thread using the constructor with argument a class implementing Runnable is one of two way to create a thread, the other is to extend the class Thread, and after you call the method start() to execute the thread.

Instead, stopping the thread is much more complicated, there is a method stop() but it is deprecated.

There are two ways to stop a thread:

  1. setting a flag
    consider a thread created with this Runnable:

    public class RunnableA implements Runnable {
    
        private volatile boolean running;
    
        public boolean isRunning() {
    	return running;
        }
    
        public void setRunning(boolean running) {
    	this.running = running;
        }
    
        @Override
        public void run() {
    	running = true;
    	while (running) {
    	    // the thread job
    	}
    	running = false;
        }
    
    }
    

    the field “running” is used in the method run() as condition to execute the loop, setting to false the method run() returns and the thread stops.
    In order to stop a thread with this Runnable you need the line:

    myThread.setRunning(false);
    

    Note that the field “running” is volatile so that any thread accessing to “running” gets the latest value.

  2. calling the method interrupt()
    with the line:

    myThread.interrupt();
    

    the thread is stopped at the first call of a method throwing the exception InterruptedException, for example wait(), join() and sleep(), as in the following:

    public class RunnableB1 implements Runnable {
    
        @Override
        public void run() {
    
    	while (true) {
    	    // the thread job
    	    try {
    		Thread.sleep(1000);
    	    } catch (InterruptedException e) {
    		e.printStackTrace();
    	    }
    	}
    
        }
    
    }
    

    If no method throwing an InterruptedException is in the code then the you have to check if the method interrupt() is called:

    public class RunnableB2 implements Runnable {
    
        @Override
        public void run() {
    
    	while (!Thread.interrupted()) {
    	    // the thread job
    	}
    
        }
    
    }
    

Comments

One response to “Stopping the threads”

  1. Excellent article Luca Zanini however I did not get the second part it will be helpful if you can explain it .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.