亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何等待多個線程完成?

如何等待多個線程完成?

嗶嗶one 2019-08-12 15:12:03
如何等待多個線程完成?簡單地等待所有線程進程完成的方法是什么?例如,假設我有:public class DoSomethingInAThread implements Runnable{     public static void main(String[] args) {         for (int n=0; n<1000; n++) {             Thread t = new Thread(new DoSomethingInAThread());             t.start();         }         // wait for all threads' run() methods to complete before continuing     }     public void run() {         // do something here     }}我如何改變這一點,以便main()方法在注釋處暫停,直到所有線程的run()方法都退出?謝謝!
查看完整描述

3 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

您將所有線程放在一個數組中,啟動它們,然后循環

for(i = 0; i < threads.length; i++)
  threads[i].join();

每個連接將阻塞,直到相應的線程完成。線程可以以與加入它們不同的順序完成,但這不是問題:當循環退出時,所有線程都完成。


查看完整回答
反對 回復 2019-08-12
?
叮當貓咪

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的并發實用程序的所有新東西)非常靈活,上面的示例幾乎沒有表面上的劃痕。


查看完整回答
反對 回復 2019-08-12
?
長風秋雁

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
   }}


查看完整回答
反對 回復 2019-08-12
  • 3 回答
  • 0 關注
  • 492 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號