java promise

java 模拟javascripe的promise 

必须通过Callable接口,通过主线程阻塞监听 futures[j].get(); 来保证任务执行完毕. 示例代码

public class TestV {

public static List<Integer> list = Collections.synchronizedList(new ArrayList<>());

public static void main(String[] args) {
Future<Boolean>[] futures=new Future[10000];
for(int i=0; i<10000; i++) {
BatchCall c = new BatchCall(i);
futures[i] = ThreadPoolUtil.executor.submit(c);
}
for(int j=0; j<10000; j++) {
try{
futures[j].get();
}catch (Exception e) {
System.out.println(futures.length);
e.printStackTrace();
}
}
System.out.println(list.size());
}

}

class BatchCall implements Callable {
private int i;
public BatchCall() {
}

public BatchCall(int i) {
this.i = i;
}

@Override
public Object call() throws Exception {
TestV.list.add(1);
Thread.sleep(2);
System.out.println(this.i);
return true;
}
}

  

posted @ 2022-11-28 11:52  trump2  阅读(234)  评论(0)    收藏  举报