3 回答

TA貢獻1828條經驗 獲得超13個贊
您將所有線程放在一個數組中,啟動它們,然后循環
for(i = 0; i < threads.length; i++) threads[i].join();
每個連接將阻塞,直到相應的線程完成。線程可以以與加入它們不同的順序完成,但這不是問題:當循環退出時,所有線程都完成。

TA貢獻1776條經驗 獲得超12個贊
一種方法是做一個List的ThreadS,創建和啟動每個線程,而將其添加到列表中。一旦啟動所有內容,循環回列表并調用join()每個列表。線程完成執行的順序并不重要,您需要知道的是,當第二個循環完成執行時,每個線程都將完成。
更好的方法是使用ExecutorService及其相關方法:
List<Callable> callables = ... // assemble list of Callables here
// Like Runnable but can return a value
ExecutorService execSvc = Executors.newCachedThreadPool();
List<Future<?>> results = execSvc.invokeAll(callables);
// Note: You may not care about the return values, in which case don't
// bother saving them
使用ExecutorService(以及來自Java 5的并發實用程序的所有新東西)非常靈活,上面的示例幾乎沒有表面上的劃痕。

TA貢獻1757條經驗 獲得超7個贊
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class DoSomethingInAThread implements Runnable{ public static void main(String[] args) throws ExecutionException, InterruptedException { //limit the number of actual threads int poolSize = 10; ExecutorService service = Executors.newFixedThreadPool(poolSize); List<Future<Runnable>> futures = new ArrayList<Future<Runnable>>(); for (int n = 0; n < 1000; n++) { Future f = service.submit(new DoSomethingInAThread()); futures.add(f); } // wait for all tasks to complete before continuing for (Future<Runnable> f : futures) { f.get(); } //shut down the executor service so that this thread can exit service.shutdownNow(); } public void run() { // do something here }}
添加回答
舉報