ExecutorService pool2 = Executors.newSingleThreadExecutor();
Future result2 = pool2.submit(new FutureTask<String>(
new Callable<String>() {
public String call() throws Exception {
return "TEST";
}
}));
String res2 = (String) result2.get();
Thread.sleep(5000);
System.out.println(res2);// 结果怎么是null,我以为是 "TEST" 呢
结果为什么是null呢
java 线程池
------解决方案--------------------
public static void main(final String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool2 = Executors.newSingleThreadExecutor();
Future<String> result2 = pool2.submit(new Callable<String>() {
public String call() throws Exception {
return "TEST";
}
});
Thread.sleep(1000);
String res2 = result2.get();
System.out.println(res2);
}
FutureTask要通过execute方法调用,submit直接传入callable。你这个程序如果用FutureTask来实现要这样:
public static void main(final String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool2 = Executors.newSingleThreadExecutor();
FutureTask<String> task = new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
return "TEST";
}
});
pool2.execute(task);
Thread.sleep(100);
if (task.isDone())