您可以使用以下代码,这些代码只使用java6提供的功能:
public static boolean waitFor(Process p, long t, TimeUnit u) {
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
final AtomicReference<Thread> me = new AtomicReference<Thread>(Thread.currentThread());
ScheduledFuture<?> f = ses.schedule(new Runnable() {
@Override public void run() {
Thread t = me.getAndSet(null);
if(t != null) {
t.interrupt();
me.set(t);
}
}
}, t, u);
try {
p.waitFor();
return true;
}
catch(InterruptedException ex) {
return false;
}
finally {
f.cancel(true);
ses.shutdown();
// ensure that the caller doesn't get a spurious interrupt in case of bad timing
while(!me.compareAndSet(Thread.currentThread(), null)) Thread.yield();
Thread.interrupted();
}
}
注意,与其他解决方案不同,您可以在某个地方找到它,它将执行
Process.waitFor()
在调用者线程中调用,这是使用监视工具查看应用程序时所期望的。它也有助于短时间运行的子进程的性能,因为调用方线程不会比
进程.waitfor()
,即不需要等待后台线程完成。相反,在后台thead中发生的是,如果超时时间已过,初始化线程将被中断。