请教如下方式是否可以等到所有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();
          }

解决方案 »

  1.   

    如果其中某个join()泡了异常,后面的join()就全部被忽略了,因为直接进入catch里面去了。
      

  2.   

    你是想某个join出了异常catch,并且线程还继续是么?
      

  3.   

    那你就在每个join之前判断一下这10个P是否都已start。
    static int num = 0;
    重写start()方法
    public void start(){
     start();
     num++;
    }在每次join()之前判断一下num,如果=10就join();如果!=10就不执行。这个num就是信号量。
    定义没找过,个人感觉不是他。
      

  4.   

    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();
    }

    }
      

  5.   


    信号量技术,关键类Semaphore
    import java.util.concurrent.Semaphore;public class Test
    {
    public static void main(String[] args)
    {
    Semaphore semaphore = new Semaphore(0);
    for (int i = 0; i < 10; i++)
    {
    new TestThread(i, semaphore).start();
    }

    try 
    {
    semaphore.acquire(10); //需要10个信号量才能继续
    }
    catch (InterruptedException e) 
    {
    e.printStackTrace();
    }

    System.out.println("finished!");
    }
    }class TestThread extends Thread
    {
    private int i;
    private Semaphore semaphore;

    public TestThread(int i, Semaphore semaphore)
    {
    this.i = i;
    this.semaphore = semaphore;
    }

    public void run()
    {
    try 
    {
    Thread.sleep(1000);
    System.out.println("线程" + i + "结束");
    }
    catch (InterruptedException e) 
    {
    e.printStackTrace();
    }

    semaphore.release(); //每结束一个线程,释放一个信号量
    }
    }