Possible Duplicate:
How do you kill a thread in Java?
How to start/stop/restart a thread in Java?
Thread
has the following functions:
destroy()
stop()
suspend()
but they are all deprecated.
What do you use to stop a thread?
Possible Duplicate:
How do you kill a thread in Java?
How to start/stop/restart a thread in Java?
Thread
has the following functions:
destroy()
stop()
suspend()
but they are all deprecated.
What do you use to stop a thread?
You should make sure that it just runs through / exits itself when its supposed to.
Check this for explanation.
You can use a boolean flag to stop the thread. Also you can make use of Thread.isInterrupted() to check if thread was interrupted and ignore the rest of the work same as boolean flag.
class Worker implements Runnable {
private volatile boolean shouldRun = true;
@Override
public void run() {
while (shouldRun) {
// your code here
}
}
public void cancel()
{
shouldRun = false;
}
}
If you wan to know why these functions are deprecated you can check Java Thread Primitive Deprecation
You could do it like this:
private boolean running = true;
public void stop () {
running = false;
}
public void run () {
while (running) {
//your code goes here
}
}
This is just a simple way of letting the run-method simply die out.
You ask him politely to end it's work. The thread should be well behaved and it should end it's work when asked.
To ask you use Thread.interrupt()
which will either throw in InterruptedException
(if the thread is waiting) or set a flag in the thread (if not waiting).
The thread should then exit it's work when it catches an InterruptException
or if it does a lot a long work (without sleep/wait) it should check from time to time if it was interrupted and exit if so.
The methods you mentioned are deprecated because once used they could bring system to unstable state: it is just like kill process. Using these methods does not give the thread any chance to exit gracefully.
The conclusion is that each thread you are implementing should have its own mechanism for graceful exit. Typically you do the following. Create boolean
flag exit
that is false
by default. The thread's run()
method should implement loop like:
while (!exit) {
// do the job
}
Add method exit()
that turns this flag to true
, so when the method is called from outside your thread will leave the while
loop at the next iteration. You should care about closing resources etc when exiting.
Obviously you can improve the mechanism by sending sing
Any thread runs to do its work. It should determine itself if there is more work to do. When you want to stop a working thread, this means the thread thinks the work exists, but you do not want the thread to do it. This is definitely a problem in your design. In a good designed problem, there is no need to stop/resume threads.