2015-03-31 137 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