Starting a thread is very easy in java, after you create it you need to call the method start(), for example:
1 2 |
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:
- setting a flag
consider a thread created with this Runnable:
12345678910111213141516171819202122]public class RunnableA implements Runnable {private volatile boolean running;public boolean isRunning() {return running;}public void setRunning(boolean running) {this.running = running;}@Overridepublic 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:
1myThread.setRunning(false);
Note that the field “running” is volatile so that any thread accessing to “running” gets the latest value. - calling the method interrupt()
with the line:
1myThread.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:
1234567891011121314151617]public class RunnableB1 implements Runnable {@Overridepublic void run() {while (true) {// the thread jobtry {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:
123456789101112]public class RunnableB2 implements Runnable {@Overridepublic void run() {while (!Thread.interrupted()) {// the thread job}}}
One reply on “Stopping the threads”
Excellent article Luca Zanini however I did not get the second part it will be helpful if you can explain it .