Java 如何判断线程池所有任务是否执行完毕

2025-01-19 12:47:07
推荐回答(1个)
回答1:

可以弄个List存放所有任务,任务完成了就删掉。 大概代码如下,你可以调试看看 private ExecutorService threadPool; private List> loadTasks; private List> loadResults; private int numberOfTasks; public void load() { threadPool = Executors.newCachedThreadPool(); loadTasks = new ArrayList>(); // loadTasks.add( new Callable() { public Boolean call() throws Exception { //add one task } }); //add some other tasks loadResults = new ArrayList>(); for( Callable task : loadTasks ) { loadResults.add( threadPool.submit( task ) ); } numberOfTasks = loadResults.size(); } public float getLoadPercent() { Iterator> it = loadResults.iterator(); while (it.hasNext()) { Future next = it.next(); if (next.isDone()) { try { if (next.get()) { it.remove(); } } catch (Exception ex) { ex.printStackTrace(); } } } float percent = (numberOfTasks - loadResults.size()) / (float) numberOfTasks; return percent; }