2015-03-31 96 views
0

直接提問。是Thread.join(x)開始從start()方法被調用還是從join(x)方法被調用的時間開始計數?多線程連接(Long millis)操作

爲了演示:以下哪種解決方案是正確的做法?

 Set<Thread> myThreads=new HashSet<Thread>(); 
     for(Task t : tasks){ 
      try{ 
       Thread thread=new ConcurrentTask(t); 
       thread.start(); 
       myThreads.add(thread); 
       Thread.sleep(1000); 
      }catch(Exception e){ 

      } 
     } 
//solution 1: 
     for(Thread t: myThreads){ 
      try{ 
       t.join(10000) //wait for at most 10 seconds 
      }catch(Exception e){} 
     } 
//solution 2: 
     long maxWaitTime=System.currentTimeMillis()+ (10*1000);//max wait is 10 seconds; 
     for(Thread t: myThreads){ 
      long threadWait=maxWaitTime - System.currentTimeMillis(); 
      if(threadWait<100){ 
       threadWait=100; 
      } 
      try{ 
       t.join(threadWait) //wait for at most 10 seconds 
      }catch(Exception e){} 

     } 
+3

[_等待這個線程死亡的最大毫秒數。超時時間爲0意味着永遠等待._](http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#join-long-)它在「加入」時開始計數被調用。 – 2015-03-31 15:33:02

回答

0

既然你是做多線程,它看起來像的最長等待時間爲所有線程應該是10秒鐘,然後選擇2是正確的。等待時間來自等待執行,它不會檢查總線程執行時間。

+0

所以,讓我們說使用解決方案1,如果有10個線程,那麼程序可以持續100秒。是對的嗎? – nafas 2015-03-31 15:44:38

+0

最糟糕的情況是,加上每次等待之間的開銷。對於#2,最壞的情況是10秒+ .1秒x(線程數-1)加上任何開銷。 – Necreaux 2015-03-31 16:43:13