Wednesday, June 24, 2009

How to Stop a Thread


There are two methods(stop() and suspend()) available in Thread class to stop the thread. As these methods are deprecated, it is advisable not to use these methods and use below mentioned approach to stop the thread.

// Create and start the thread
SampleThread thread = new SampleThread();
thread.start();
//...Some Code...
// Stop the thread
thread.done = true;

class SampleThread extends Thread {
boolean done = false;
// This method is called when the thread runs
public void run() {
while (true) {
// ...Some Code...
if (done) {
return;
}
// ...Some Code...
}
}
}

1 comments:

Javin @ hashmap in Java on November 4, 2011 at 10:15 PM said...

Great post man. Even though Java's Thread and Concurrency API is quite reach it doesn't provide any safe method to stop a Thread or reuse a Thread directly. Though Executor framework some what handles this by using worker thread but in many scenario a direct control is needed. By the way here is mine way of Stopping Thread in Java

 

Sample Java Codes Copyright © 2008 Green Scrapbook Diary Designed by SimplyWP | Made free by Scrapbooking Software | Bloggerized by Ipiet Notez