直接提问。是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){}
}
[_等待这个线程死亡的最大毫秒数。超时时间为0意味着永远等待._](http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#join-long-)它在“加入”时开始计数被调用。 – 2015-03-31 15:33:02