【问题标题】:Using Executor & Runnable together to kill threads after some time一段时间后一起使用 Executor & Runnable 杀死线程
【发布时间】:2014-02-24 05:34:06
【问题描述】:

我碰巧看到这篇文章在使用 Executor 服务一段时间后杀死一个线程:Killing thread after some specified time limit in Java

这是文章中提到的代码:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new Task()), 10, TimeUnit.MINUTES); // Timeout of 10 minutes.
executor.shutdown();

现在我的程序中有一个可运行的线程要执行。如何在使用上述代码一段时间后终止该线程?

这是我用于创建线程的代码的一部分:

public static List<Thread> thread_starter(List<Thread> threads,String filename)
{   String text=read_from_temp(filename);
     Runnable task = new MyRunnable(text);
     Thread worker = new Thread(task);  
     worker.start();
      // Remember the thread for later usage
     threads.add(worker);
    return threads;
}

public class MyRunnable implements Runnable {
MyRunnable(String text)
{ 
this.text=text;
}
@Override
public void run() {
  /* other computation*/
}

我通过调用 thread_started() 函数创建多个线程。

谁能帮我将 Executor Service 与它结合起来。我尝试了很多,但找不到任何出路!

【问题讨论】:

标签: java multithreading runnable executorservice


【解决方案1】:

在java中,你不能直接杀死一个正在运行的线程。如果你想杀死你正在运行的线程,你需要在你的任务中设置一个运行标志,在线程任务中检查它,并将它设置在外面。例如:

   MyRunnable task = ....;
   ......
   task.running = false;  //stop one task


   public class MyRunnable implements Runnable {
       public boolean running = true;
       public void run() {
            while(running){
                 .....
            }
       }

你提到的'ExecutorService'是单线程'ExecutorService',它会一个一个地执行任务,它对超时所做的只是等待一个任务完成并计算/比较每个任务的超时时间。你可以在java的源代码'AbstractExecutorService.java'中找到它。

【讨论】:

    猜你喜欢
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多