【问题标题】:Stop a Runnable in a Thread imediatly立即停止线程中的 Runnable
【发布时间】:2015-01-07 00:54:24
【问题描述】:

我尝试在 java 中使用某种包含一些线程对象的调度程序来实现一个软件事务内存库版本。我想实现一种机制,调度程序告诉线程立即停止执行,删除它的 Runnable,创建一个新的并重新运行它。到目前为止,这真的是半熟,但我不想要的是重新创建洞线程,因为它将作为几个变量的状态持有者(只有线程具有的其他变量的深拷贝 - 复制任务在这里是一个阻塞,所以线程不应完全重新创建)

我的问题是我不知道在方法执行时终止方法并释放所有资源的任何事情(如果调度程序告诉线程重新启动 Runnable 所做的一切都是无效的并且必须重做)并开始运行再次使用新的输入变量方法。

目标是避免不必要的执行,并且runnable中不应该有变量询问它是否被中断然后跳过执行或其他东西。只需停止执行并从可运行本身不知道的东西中杀死它。我希望很清楚我想要什么如果不是请询问不清楚的点帮助将不胜感激:)

【问题讨论】:

  • 这是不可能的。线程必须有一些信号告诉它停止(为什么有中断机制),否则它将继续运行直到完成。您可以使用已弃用的方法Thread#stop,但这不会进行任何清理。
  • @Quirliom:我想知道您是否不能通过执行操作系统调用来终止线程。毕竟,操作系统决定了哪些线程可以控制 CPU。
  • @CommuSoft 使用 Java?不太可能。
  • @Quirliom:旧版本的 java 确实有虚拟机定义的方法,但后来 Java 切换到 POSIX 线程。主要是因为性能问题。
  • 使用 ExecutorService 并维护对 Future 的引用并使用它的取消方法。如果当前线程,您的可运行对象将需要监视中断状态

标签: java multithreading stm


【解决方案1】:

取消 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;
            }
        }
    }
}
}

【讨论】:

  • 谢谢,看来我得在这里看看期货了。
猜你喜欢
  • 2015-12-04
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
相关资源
最近更新 更多