0

所以我有我的 MainThread 类负责所有其他线程。(创建、停止、监视)

 public class MainThread implements Runnable {
      public static volatile boolean keepRunning = true;  

      public void run(){


      //some code..


      while(keepRunning){

      //here i am creating threads for my Wired class (explaining below) 
      //that are stored in a hashmap

      Wired wiredInterface = new Wired(s,defaultSleepTime,c,max,percent);
      Thread t1 = new Thread(wiredInterface);
      t1.start();
      }

在我的代码中,有一种情况我需要停止线程 t1。

我的有线课堂:

   public class Wired implements Runnable {
        private static volatile boolean keepRunning = true;

        public void run(){

        while(keepRunning){

        //code

        try{
            Thread.sleep(((k - i + 1)*defaultTime) - DT);  //just to show that this thread sleeps periodically. doesnt affect the question
        }catch(InterruptedException e){e.printStackTrace();}  

        }
        }

在我的有线课程中,我有这种方法来更改 volatile 标志。

        public static void stopRunning(){
            keepRunning = false;
        }

我的问题是..如何从我的 MainThread 访问方法 stopRunning 以获得我想要停止的特定线程?Thread.interrupt() 作为解决方案对我不起作用。

我看过很多关于这个主题的类似问题,但我还没有找到适合我的情况的东西。抱歉,如果我遗漏了什么此代码是对我的实际代码的过度简化

4

2 回答 2

1

不要在这里重新发明轮子。使用 Thread.interrupt(),并正确检查 Thread.isInterrupted() 标志,和/或正确处理 InterruptedException。IE 不要吞下它或 printStackTrace() 它并继续。如果您收到一个 InterruptedException,请在 Runanble.run() 方法的边界捕获它并停止您的外部循环并关闭线程。

您的方法应更改为:

public void run() {
   try {
      while( !Thread.currentThread().isInterrupted() ) {
          doSomeThreadedThing();
      }
   } catch( InterruptedException e ) {
      // maybe log some info you are shutting down
   }
}

只要线程没有卡在某些 IO 中,正确关闭线程真的很简单。如果您不想等待长时间运行的任务,请定期检查逻辑中的 Thread.isInterrupted()。与使用 Thread.interrupted() 相比,您的 volatile 布尔标志机制没有提供任何优势。

于 2012-11-19T20:23:02.063 回答
1

您应该让 keepRunning 成为一个实例变量(属性)而不是静态的。

每当您想停止线程时,从 Map 中获取它并使用 setKeepRunning(false) 将属性 keepRunning 设置为 false。

于 2012-11-19T20:18:48.817 回答