所以我有我的 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();}
}
}
在我的 Wired 类中,我有这个方法来更改易失性标志。
public static void stopRunning(){
keepRunning = false;
}
我的问题是..如何访问方法stopRunning从我的主线程运行,用于我要停止的特定线程?Thread.interrupt() 作为解决方案对我不起作用。
我看过很多关于这个主题的类似问题,但我还没有找到适合我的情况的东西。对不起,如果我错过了什么这段代码是我实际代码的过度简化
不要在这里重新发明轮子。 使用 Thread.interrupt(),并正确检查 Thread.isInterrupted() 标志,和/或正确处理 InterruptedException。 IE不要吞下它或打印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 中。 如果你有一个长时间运行的任务,你不想等待,定期检查逻辑中的 Thread.isInterrupted()。 使用Thread.interrupted()显示的易失性布尔标志机制没有任何优势。
你应该使keepRunning成为实例变量(属性)而不是静态变量。
每当你想要停止一个线程时,从地图中获取它,并使用setKeepRunning(false)将属性keepRunning设置为false。