日期:2014-05-20  浏览次数:20690 次

请教等所有Thread结束后再往下走的问题
请教如下方式是否可以等到所有Thread都结束后牙再往下运行


SimpleThread p1=new SimpleThread(result,al1);
p1.start();
SimpleThread p2=(new SimpleThread(result,al2));
p2.start();
SimpleThread p3=(new SimpleThread(result,al3));
p3.start();
SimpleThread p4=(new SimpleThread(result,al4));
p4.start();
SimpleThread p5=(new SimpleThread(result,al5));
p5.start();
SimpleThread p6=(new SimpleThread(result,al6));
p6.start();
SimpleThread p7=(new SimpleThread(result,al7));
p7.start();
SimpleThread p8=(new SimpleThread(result,al8));
p8.start();
SimpleThread p9=(new SimpleThread(result,al9));
p9.start();
SimpleThread p10=(new SimpleThread(result,al10));
p10.start();

try {
p1.join();
p2.join();
p3.join();
p4.join();
p5.join();
p6.join();
p7.join();
p8.join();
p9.join();
p10.join();
} catch (InterruptedException e) {
e.printStackTrace();
}


------解决方案--------------------
如果其中某个join()泡了异常,后面的join()就全部被忽略了,因为直接进入catch里面去了。
------解决方案--------------------
正常情况可以。异常情况,如一楼所说,无法达到目的。
------解决方案--------------------
楼主可以采用信号量技术,解决上述问题。
------解决方案--------------------
用CountDownLatch即可
------解决方案--------------------
你是想某个join出了异常catch,并且线程还继续是么?
------解决方案--------------------
那你就在每个join之前判断一下这10个P是否都已start。
static int num = 0;
重写start()方法
public void start(){
 start();
 num++;
}

在每次join()之前判断一下num,如果=10就join();如果!=10就不执行。

这个num就是信号量。
定义没找过,个人感觉不是他。

------解决方案--------------------
Java code


public class TestCountDownLatch {

    private Thread[] threads;
    
    public TestCountDownLatch(final CountDownLatch sign, int n){
        
        threads = new Thread[n];
        for(int i=0;i<n;i++)
        {
            threads[i] = new Thread(new Runnable(){

                @Override
                public void run() {                    
                    System.out.println("work");
                    sign.countDown();
                }
                
            });
            threads[i].start();
        }
        
    }

    public static void main(String[] args) {
        
        CountDownLatch sign = new CountDownLatch(10);
        new TestCountDownLatch(sign, 10);
        try {
            sign.await();
            System.out.println("Main exit");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
    }

------解决方案--------------------
探讨

引用:

楼主可以采用信号量技术,解决上述问题。


请教如何使用?