在java中使用易失性布尔标志从hashmap中的另一个线程停止线程

在java中使用易失性布尔标志从hashmap中的另一个线程停止线程,java,multithreading,Java,Multithreading,因此,我有一个MainThread类,负责所有其他线程。(创建、停止、监视) 在我的代码中,有一种情况需要停止线程t1 我的有线课堂: public class Wired implements Runnable { private static volatile boolean keepRunning = true; public void run(){ while(keepRunning){ //code

因此,我有一个MainThread类,负责所有其他线程。(创建、停止、监视)

在我的代码中,有一种情况需要停止线程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();}  

        }
        }
在我的Wired类中,我有这个方法来更改volatile标志

        public static void stopRunning(){
            keepRunning = false;
        }
我的问题是..对于要停止的特定线程,如何从主线程访问stopRunning方法?Thread.interrupt()作为解决方案对我不起作用

我已经研究了很多与这个主题相关的类似问题,但我还没有找到适合我的案例。对不起,我错过了什么
这段代码过于简化了我的实际代码

您应该将keepRunning设置为实例变量(属性),而不是静态的


每当你想要停止一个线程时,从映射中抓取它,并使用setKeepRunning(false)将属性keepRunning设置为false。

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

您的方法应更改为:

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

只要线程没有卡在某些IO中,就可以很容易地正确关闭线程。如果您有一个长时间运行的任务,您不想在逻辑中周期性地等待check Thread.isInterrupted()。与使用Thread.interrupted()相比,您所展示的volatile boolean标志机制没有任何优势。

请详细说明
interrupt
不起作用的原因。如果有什么区别的话,它只能比你的DYI机制工作得更好。你把它设为静态的,所以它只是Wired.stopRunning(),它将应用于所有线程。不要认为这是您想要的?中断对您不起作用,因为您没有检查interrupted标志,并且忽略InterruptedExceptions。在(!Thread.currentThread().isInterrupted())时使用
,并在收到InterruptedException时立即停止循环。@如果我将其设置为静态,因为在应用程序结束时,我的所有线程都将通过shutdownHook停止。你是对的,在这种情况下我只想停止一个线程,静态不会工作。如果它在睡眠时接收到中断信号,可以吗?感谢您的回答,即使他们要求我们使用volatile flag,它看起来确实更好。事实上,这正是中断优于volatile变量的原因。中断睡眠线程将使is立即脱离睡眠状态并抛出InterruptedException,从而允许立即停止线程。设置volatile标志在睡眠时间结束之前不会有任何效果,因此,如果线程睡眠2小时,线程只会在2小时后停止。几乎所有的阻塞方法都是一样的(
wait()
lock()
,等等)
public void run() {
   try {
      while( !Thread.currentThread().isInterrupted() ) {
          doSomeThreadedThing();
      }
   } catch( InterruptedException e ) {
      // maybe log some info you are shutting down
   }
}