实际上,宁愿使用 ExecutorService
而不是 ,下面是一个 SSCCE:Timer
package com.stackoverflow.q2275443;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Task());
try {
System.out.println("Started..");
System.out.println(future.get(3, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
future.cancel(true);
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
class Task implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
return "Ready!";
}
}
在 Future#get()
方法中稍微玩一下参数,例如,将其增加到 5,你会看到线程完成。您可以截获块中的超时。timeout
catch (TimeoutException e)
更新:澄清一个概念上的误解,不是必需的。它仅用于 SSCCE/演示目的。只需在那里执行长时间运行的任务即可代替 。在长时间运行的任务中,您应该检查线程是否未中断,如下所示:sleep()
sleep()
while (!Thread.interrupted()) {
// Do your long running task here.
}