How to stop a thread created by implementing runnable interface?

前端 未结 6 2157
独厮守ぢ
独厮守ぢ 2020-11-27 13:08

I have created class by implementing runnable interface and then created many threads(nearly 10) in some other class of my project.
How to stop some of those threads?

相关标签:
6条回答
  • 2020-11-27 13:40

    The simplest way is to interrupt() it, which will cause Thread.currentThread().isInterrupted() to return true, and may also throw an InterruptedException under certain circumstances where the Thread is waiting, for example Thread.sleep(), otherThread.join(), object.wait() etc.

    Inside the run() method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted() value and do something (for example, break out).

    Note: Although Thread.interrupted() seems the same as isInterrupted(), it has a nasty side effect: Calling interrupted() clears the interrupted flag, whereas calling isInterrupted() does not.

    Other non-interrupting methods involve the use of "stop" (volatile) flags that the running Thread monitors.

    0 讨论(0)
  • 2020-11-27 13:41

    Stopping (Killing) a thread mid-way is not recommended. The API is actually deprecated.

    However,you can get more details including workarounds here: How do you kill a thread in Java?

    0 讨论(0)
  • 2020-11-27 13:43

    How to stop a thread created by implementing runnable interface?

    There are many ways that you can stop a thread but all of them take specific code to do so. A typical way to stop a thread is to have a volatile boolean shutdown field that the thread checks every so often:

      // set this to true to stop the thread
      volatile boolean shutdown = false;
      ...
      public void run() {
          while (!shutdown) {
              // continue processing
          }
      }
    

    You can also interrupt the thread which causes sleep(), wait(), and some other methods to throw InterruptedException. You also should test for the thread interrupt flag with something like:

      public void run() {
          while (!Thread.currentThread().isInterrupted()) {
              // continue processing
              try {
                  Thread.sleep(1000);
              } catch (InterruptedException e) {
                  // good practice
                  Thread.currentThread().interrupt();
                  return;
              }
          }
      }
    

    Note that that interrupting a thread with interrupt() will not necessarily cause it to throw an exception immediately. Only if you are in a method that is interruptible will the InterruptedException be thrown.

    If you want to add a shutdown() method to your class which implements Runnable, you should define your own class like:

    public class MyRunnable implements Runnable {
        private volatile boolean shutdown;
        public void run() {
            while (!shutdown) {
                ...
            }
        }
        public void shutdown() {
            shutdown = true;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 13:52

    If you use ThreadPoolExecutor, and you use submit() method, it will give you a Future back. You can call cancel() on the returned Future to stop your Runnable task.

    0 讨论(0)
  • 2020-11-27 13:54

    Stopping the thread in midway is not a good practice. More appropriate way is to make the thread return programmatically. Let the Runnable object use a shared variable in the run() method. Whenever you want the thread to stop, use that variable as a flag.

    EDIT: Sample code

    class MyThread implements Runnable{
    
        private Boolean stop = false;
    
        public void run(){
    
            while(!stop){
    
                //some business logic
            }
        }
        public Boolean getStop() {
            return stop;
        }
    
        public void setStop(Boolean stop) {
            this.stop = stop;
        }       
    }
    
    public class TestStop {
    
        public static void main(String[] args){
    
            MyThread myThread = new MyThread();
            Thread th = new Thread(myThread);
            th.start();
    
            //Some logic goes there to decide whether to 
            //stop the thread or not. 
    
            //This will compell the thread to stop
            myThread.setStop(true);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 14:04

    Thread.currentThread().isInterrupted() is superbly working. but this code is only pause the timer.

    This code is stop and reset the thread timer. h1 is handler name. This code is add on inside your button click listener. w_h =minutes w_m =milli sec i=counter

     i=0;
                w_h = 0;
                w_m = 0;
    
    
                textView.setText(String.format("%02d", w_h) + ":" + String.format("%02d", w_m));
                            hl.removeCallbacksAndMessages(null);
                            Thread.currentThread().isInterrupted();
    
    
                            }
    
    
                        });
    
    
                    }`
    
    0 讨论(0)
提交回复
热议问题