Callable and Future
阿新 • • 發佈:2018-08-24
main .get thread ade throws let nds rac exe
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 {
public static void main(String[] args) {
//future有什麽用 ?等一會取得線程的執行結果
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 {
//1s之內沒有取得結果則報錯
System.out.println("拿到結果:" + future.get(1000,TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
}
//對線程池中的線程 先執行完的結果先被獲取
//類似qq農場 那塊才熟了收哪塊
ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
for(int i=1;i<=10;i++){
final int seq = i;
completionService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(new Random().nextInt(5000));
return seq;
}
});
}
for(int i=0;i<10;i++){
try {
System.out.println(
completionService.take().get());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Callable and Future