package alibaba.data.demo.utils;
import com.sun.javafx.collections.MappingChange;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
public class TheradPoll {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//創建線程池
ExecutorService executor = Executors.newCachedThreadPool();
//提交任務並獲取執行結果
List<Future<Object>> futureList = new LinkedList<>();
futureList.add(executor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
//假數據
Map<String,String> map = new HashMap<>();
for(int i=0;i<10;i++){
map.put(i+"","0假數據"+i);
}
return map;
}
})
);
futureList.add(executor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
//假數據
Map<String,String> map = new HashMap<>();
for(int i=0;i<16;i++){
map.put(i+"","1假數據"+i);
}
return map;
}
})
);
//關閉線程池
executor.shutdown();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("主線程在執行任務");
try {
for (Future<Object> future : futureList){
if(future.get()!=null){
System.out.println("task運行結果"+future.get().toString());
}else{
System.out.println("未獲取到結果");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("所有任務執行完畢");
}
}
java Callable 併發編程
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.