Java中還提供了可以返回值的線程池,例子如下:
[java]
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
-
- public class CallableAndFuture {
-
- /**
- * @param args
- */
- public static void main(String[] args) {
- ExecutorService threadPool = Executors.newSingleThreadExecutor();
- Future<String> future = threadPool.submit(new Callable<String>(){
-
- @Override
- public String call() throws Exception {
- Thread.sleep(3000);
- return "future";
- }
-
- });
- try {
- System.out.println("waiting...");
- System.out.println(future.get());
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- }
- }
-
- }
future.get()結果出來之前,要等待一會
future.get(300, TimeUnit.MILLISECONDS);然而這個如果在規定的時間內沒有完成,則停止,並且跑出超時異常
還有需要注意的地方,Callable中的泛型和call方法的類型一直,並且還要和Future的泛型類型一致。
下面的例子是,可以返回多個Future對象
[java]
- //創建線程池
- ExecutorService pool = Executors.newFixedThreadPool(10);
- //創建CompletionService實例
- CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(pool);
- //提交任務
- for(int i = 0;i < 10; i++){
- final int index = i;
- completionService.submit(new Callable<Integer>(){
-
- @Override
- public Integer call() throws Exception {
- return index;
- }
-
- });
- }
- //獲得結果
- for(int i = 0;i<10;i++){
- try {
- Future<Integer> future2 = completionService.take();
- System.out.println(future2.get());
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- }
- }
- }
不知道用在什麼地方,業務需求沒有碰到過這種情況