4

如果加入线程不起作用,建议做什么?

        for (List t : threads) {
           try {
              t.join();
           } catch (InterruptedException e) {
              log.error("Thread " + t.getId() + " interrupted: " + e);
              // and now?
           }
         }

是否建议中断(然后其他尚未加入的线程会发生什么情况?)或者您是否应该至少尝试加入其余线程然后继续?

感谢您的建议!

==>结论:您应该再次尝试加入特定线程 t 或者您应该中断该特定线程 t 并继续。

     for (List t : threads) {
        try {
          t.join();
       } catch (InterruptedException e) {    
            try {
                // try once! again:
                t.join();
            } catch (InterruptedException ex) {
                // once again exception caught, so:
                t.interrupt();
            }
         }
       }

那么您如何看待这个解决方案?做“t.interrupt()”是正确的还是应该是Thread.currentThread().interrupt(); ?

谢谢!:-)

4

1 回答 1

2

你得到一个InterruptedException因为其他一些线程中断了这个,加入,线程而不是因为join没有“工作”。引用自API 文档

InterruptedException- 如果另一个线程中断了当前线程。抛出此异常时清除当前线程的中断状态。


我建议您再次重新加入该线程,例如:

for (List t : threads) {
    while (true) {
        try {
            t.join();
            break;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            // ... and ignore the interrupt
        }
    }
}
于 2012-02-23T10:53:35.607 回答