我正在使用ExecutorService
及其阻止主程序一段时间,但我不想阻止主程序。
这是代码:
public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
ExecutorService executor = null;
try {
executor = Executors.newFixedThreadPool(1);
System.out.println("Start 1");
Runnable task = new Runnable() {
public void run() {
System.out.println("Start 2");
try {
Thread.sleep(7000);
System.out.println("Start 5");
} catch (Exception e) {
}
}
};
System.out.println("Start 3");
// executor.execute(task);
Future future = executor.submit(task);
Object result = future.get(9, TimeUnit.SECONDS);
System.out.println("Start 4");
} catch (Exception e) {
} finally {
System.out.println("finally");
executor.shutdownNow();
}
}
}
输出:
Start 1
Start 3
Start 2
Start 5
Start 4
finally
当前除非线程完成执行,否则它不会打印
Start 4
。我要寻找的是一种机制,在该机制下我们可以超时并且线程在后台运行并且不阻塞主线程? 最佳答案
您正在使用future.get(9, TimeUnit.SECONDS);
,这将等待9秒,以完成提交的线程。
如果不需要主程序等待,也不需要线程返回任何内容,请使用executor.execute
调用。
这是更新的代码...
ExecutorService executor = null;
try {
executor = Executors.newFixedThreadPool(1);
System.out.println("Start 1");
Runnable task = new Runnable() {
public void run() {
System.out.println("Start 2");
try {
Thread.sleep(7000);
System.out.println("Start 5");
}
catch (Exception e) {
}
}
};
System.out.println("Start 3");
executor.execute(task);
System.out.println("Start 4");
}
catch (Exception e) {
}
finally {
System.out.println("finally");
executor.shutdown();
}
}