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(); 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 { @Override public Object call() throws Exception { TestV.list.add(1); Thread.sleep(2); return true; }
标签:java,Future,static,new,promise,public From: https://www.cnblogs.com/trump2/p/16931816.html