我尝试使用某种保存一些线程对象的调度程序在java中实现软件事务内存库的一个版本。我想实现一种机制,调度程序告诉线程立即停止执行,删除其可运行对象,创建一个新的可运行对象并重新运行它。到目前为止,这确实是半熟的,但我不想重新创建洞线程,因为它将作为多个变量的状态持有者(只有线程具有的其他变量的深拷贝 - 复制任务在这里是一个阻塞,所以线程不应完全重新创建)
我的问题是,我不知道任何在执行方法时终止方法并释放所有资源的信息(如果调度程序告诉线程重新启动 Runnable 所做的一切都是无效的,必须重做)并开始运行使用新的输入变量再次使用方法。
目标是避免不必要的执行,并且可运行对象中不应有变量询问是否被中断,然后跳过执行或其他内容。只需停止执行并从可运行本身不知道的东西中杀死它即可。我希望我清楚我想要什么,如果不清楚,请询问不清楚的地方,我们将不胜感激:)
最佳答案
取消可运行并再次启动它的简单教程。
public class RestartThreadTutorial {
public static void main(String args[]){
ExecutorService executorService = Executors.newFixedThreadPool(5);
Future<?> taskHandler = executorService.submit(new Task());
//restart the task after 3 seconds.
try{
Thread.sleep(3000);
}catch(InterruptedException e){
//empty
}
taskHandler.cancel(true); //it will cancel the running thread
if (taskHandler.isCancelled()==true){//check the thread is cancelled
executorService.submit(new Task());//then create new thread..
}
}
public static class Task implements Runnable{
private int secondsCounter;
@Override
public void run(){
while(true){
System.out.println("Thread -"+Thread.currentThread().getName()+"elapsed - "+ (secondsCounter++) +"second");
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
break;
}
}
}
}
}
关于java - 立即停止线程中的 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27809827/