【发布时间】:2017-05-24 23:03:42
【问题描述】:
我有一个任务执行器,它将runnable 作为任务。我在调用runnable.run() 方法之前启动一个计时器,并在可运行完成时停止它。如果计时器超过时间限制,我想从执行程序本身终止run() 方法的执行。我不知道用户会在run() 中实现什么。
TaskExecutor.add(new Runnable () {
@Override
public void run() {
System.out.println("This is test job");
}}
);
这是用户添加新任务的方式。每个任务都在同一个线程中运行。
编辑
此任务执行器将充当用户的service。而且因为创建线程是一项昂贵的操作并且需要native 操作系统调用,所以我试图避免它们。否则我会在某个时候打电话给Thread.interrupt()。但我只想知道是否有办法终止父对象的run() 方法。终止意味着突然停止某事。就像我们如何在 OS 任务管理器中终止进程一样。
如何执行任务
while (jobQueue.isEmpty()) {
for (Job job : jobQueue) {
long startTime = System.currentTimeMillis();
job.run();
//There is a separate thread which checks
//for timeout flags by comparing the startTime
//with the current time. But all tasks are
//executed in the same thread sequentially. I
//only want to terminate single jobs that are
//timed out.
}
}
【问题讨论】:
-
您无法阻止任意代码运行。该方法需要通过对中断做出反应和/或轮询某些线程安全标志的值来进行协作。不,永远,永远不要使用 Thread 的 stop() 方法,因为非常好的原因,该方法已被弃用。
-
您也可以将 Runnable 包装到
java.util.concurrent.FutureTask中。它有方法 publicboolean cancel(boolean mayInterruptIfRunning)并安排get将在成功完成时返回给定的结果。 -
@JFreeman 这个问题是关于停止线程的。那不是我打算做的。
-
@JBNizet 我无法控制用户在
run()方法中实现的内容。此执行器用作服务。