Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a Java thread? [duplicate]

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?

like image 501
user1387622 Avatar asked Oct 21 '12 07:10

user1387622


2 Answers

You should make sure that it just runs through / exits itself when its supposed to.

Check this for explanation.

like image 176
Udo Held Avatar answered Sep 29 '22 21:09

Udo Held


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

like image 43
Amit Deshpande Avatar answered Sep 29 '22 22:09

Amit Deshpande