【发布时间】: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 与它结合起来。我尝试了很多,但找不到任何出路!
【问题讨论】:
-
也许你应该看看这个答案...stackoverflow.com/a/15900500/614868
标签: java multithreading runnable executorservice