通过 Future可以获取 Callable 返回的结果
future.get() 可以阻塞线程,使线程等待结果。
-
package cn.itcast.heima2;
-
-
import java.util.Random;
-
import java.util.concurrent.Callable;
-
import java.util.concurrent.CompletionService;
-
import java.util.concurrent.ExecutionException;
-
import java.util.concurrent.ExecutorCompletionService;
-
import java.util.concurrent.ExecutorService;
-
import java.util.concurrent.Executors;
-
import java.util.concurrent.Future;
-
import java.util.concurrent.TimeUnit;
-
-
-
-
public class CallableAndFuture {
-
-
/**
-
* @param args
-
*/
-
public static void main(String[] args) {
-
ExecutorService threadPool = Executors.newSingleThreadExecutor();
-
Future<String> future =
-
threadPool.submit(
-
new Callable<String>() {
-
public String call() throws Exception {
-
Thread.sleep(2000);
-
return "hello";
-
};
-
}
-
);
-
System.out.println("等待结果");
-
try {
-
System.out.println("拿到结果:" + future.get());
-
} catch (InterruptedException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
} catch (Exception e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
-
-
-
-
}
阅读(1070) | 评论(0) | 转发(0) |