我想在一段固定的时间内运行一个线程.如果它没有在那段时间内完成,我想杀死它,抛出一些异常,或以某种方式处理它.怎么做到呢?
我从这个线程 中发现的一种方法是在Thread的run()方法中使用TimerTask.
有没有更好的解决方案呢?
编辑:添加赏金,因为我需要一个更清晰的答案.下面给出的ExecutorService代码没有解决我的问题.为什么我应该在执行后睡觉()(一些代码 - 我没有处理这段代码)?如果代码完成并且sleep()被中断,那怎么可能是timeOut?
需要执行的任务不在我的控制范围内.它可以是任何一段代码.问题是这段代码可能会遇到无限循环.我不希望这种情况发生.所以,我只想在一个单独的线程中运行该任务.父线程必须等到该线程完成并且需要知道任务的状态(即它是否超时或发生了一些异常或者是否成功).如果任务进入无限循环,我的父线程会无限期地等待,这不是一个理想的情况.
我正在寻找一个可以提供超时的ExecutorService实现.提交给ExecutorService的任务如果花费的时间超过运行超时,则会中断.实现这样的野兽不是一项艰巨的任务,但我想知道是否有人知道现有的实施.
以下是我根据下面的一些讨论提出的内容.任何意见?
import java.util.List;
import java.util.concurrent.*;
public class TimeoutThreadPoolExecutor extends ThreadPoolExecutor {
private final long timeout;
private final TimeUnit timeoutUnit;
private final ScheduledExecutorService timeoutExecutor = Executors.newSingleThreadScheduledExecutor();
private final ConcurrentMap<Runnable, ScheduledFuture> runningTasks = new ConcurrentHashMap<Runnable, ScheduledFuture>();
public TimeoutThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, long timeout, TimeUnit timeoutUnit) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
this.timeout = timeout;
this.timeoutUnit = timeoutUnit;
}
public TimeoutThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, long timeout, …Run Code Online (Sandbox Code Playgroud) 我想测试安装的网络驱动器上是否存在文件.
我用这个简单的代码写了File.exists.
import java.io.File;
public class NetworkDrive {
public static void main(String[] args) {
System.err.println(new File("/Volumes/DATA/testedFile.txt").exists());
}
}
Run Code Online (Sandbox Code Playgroud)
它大部分工作正常,但我发现这个代码有问题的边缘情况.如果驱动器已安装且由于某种原因网络连接失败,则程序会挂起很长时间(10分钟).
time java NetworkDrive
false
real 10m6.114s
user 0m0.431s
sys 0m0.949s
Run Code Online (Sandbox Code Playgroud)
即使我尝试使用KILL信号杀死它,该过程仍在运行.
1875 ttys000 0:00.00 (java)
Run Code Online (Sandbox Code Playgroud)
问题是这样的java.nio:
Files.exists(Paths.get("/Volumes/DATA/testedFile.txt"));
Run Code Online (Sandbox Code Playgroud)
我在OS X Yosemite上使用java版本1.8.0_20.