如何停止通过实现runnable接口创建的线程?

时间:2012-05-17 06:14:52

标签: java multithreading thread-safety

我通过实现runnable接口创建了类,然后在我项目的其他一些类中创建了许多线程(接近10个)。
如何阻止其中一些线程?

6 个答案:

答案 0 :(得分:67)

最简单的方式是interrupt()它,这会导致Thread.currentThread().isInterrupted()返回true,并且可能会在某些情况下抛出InterruptedException线程等待的情况,例如Thread.sleep()otherThread.join()object.wait()等。

run()方法中,您需要捕获该异常和/或定期检查Thread.currentThread().isInterrupted()值并执行某些操作(例如,突破)。

注意:虽然Thread.interrupted()似乎与isInterrupted()相同,但它有一个令人讨厌的副作用:调用interrupted() 清除 interrupted标记,而调用isInterrupted()却没有。

其他非中断方法涉及使用正在运行的线程监视的“stop”(volatile)标记。

答案 1 :(得分:33)

  

如何停止通过实现runnable接口创建的线程?

有很多方法可以阻止线程,但是所有这些方法都需要特定的代码来执行此操作。停止线程的一种典型方法是让线程经常检查volatile boolean shutdown字段:

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

您还可以中断导致sleep()wait()和其他一些方法抛出InterruptedException的线程。您还应该测试线程中断标志,例如:

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

请注意,使用interrupt()中断线程必然会导致它立即引发异常。只有当你处于可中断的方法时才会抛出InterruptedException

如果要在实现shutdown()的类中添加Runnable方法,则应定义自己的类,如:

public class MyRunnable implements Runnable {
    private volatile boolean shutdown;
    public void run() {
        while (!shutdown) {
            ...
        }
    }
    public void shutdown() {
        shutdown = true;
    }
}

答案 2 :(得分:9)

中途停止线程不是一个好习惯。更合适的方法是使线程以编程方式返回。让Runnable对象在run()方法中使用共享变量。每当您希望线程停止时,请将该变量用作标志。

编辑:示例代码

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);
    }
}

答案 3 :(得分:5)

如果您使用ThreadPoolExecutor并使用submit()方法,则会返回Future。您可以在返回的Future上致电cancel()以停止Runnable任务。

答案 4 :(得分:1)

建议不要在中途停止(杀死)线程。该API实际上已弃用。

但是,您可以在此处获取更多详细信息,包括解决方法:How do you kill a thread in Java?

答案 5 :(得分:0)

  

Thread.currentThread()。isInterrupted()非常出色。但是这个   代码只是暂停计时器。

     

此代码停止并重置线程计时器。    h1是处理程序名称。   此代码将添加到按钮单击侦听器中。   w_h =分钟w_m =毫秒秒i =计数器

 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();


                        }


                    });


                }`