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...
}
}
}
Subscribe to:
Post Comments (Atom)
1 comments:
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
Post a Comment