比如有一个main线程。
在main thread中产生一个子线程subThread,当在subThread.start()之后 若再用subThread.join()方法会产生这样的效果:
main thread会暂时block住,直到subThread结束。 这个大家都知道。我想问,
如果我在main thread中需要产生5个subThread,这5个subThread我希望他们交替运行并且在他们运行的过程中main thread需要被block住。最后当5个subThread都结束的时候,main thread继续运行。 请问如何实现?

解决方案 »

  1.   

    在main中直接
    for(int i = 0; i < count; i++)
      t[i].join();
    就可以了,自然会等待所有的线程结束。
      

  2.   


    public class Join {
    public static void main(String[] args) throws InterruptedException {
    System.out.println("main start");
    //  for(int i=0; i<5; i++){
    // Thread t = new Thread(new Threads(i));
    // t.start();
    // t.join(); //这样直接start后就join,这些不会交替运行
    // }

    Thread[] threads = new Thread[5];
    for(int i=0; i<5; i++){
    Thread t = new Thread(new Threads(i));
    t.start();
    threads[i] = t;
    }
    for(int j=0; j<threads.length; j++){
    threads[j].join();
    }
    System.out.println("main end");
    }}
    class Threads implements Runnable{
    int id;
        public Threads(int i){
         this.id = i;
        }
    public void run() {
    // TODO Auto-generated method stub
    for(int i=0; i<10; i++){
    try {
    Thread.sleep(500);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println("---- Thread"+id);
    }
    }

    }
      

  3.   

     Thread[] threads = new Thread[5];
            for(int i=0; i<5; i++){
                Thread t = new Thread(new Threads(i));
                t.start();
                threads[i] = t;
            }
            for(int j=0; j<threads.length; j++){
                threads[j].join();
            }
      

  4.   

    如果想认为控制交替的话,可以用一个单独的调度线程来调度这5个线程的交替执行(信号量,interrupt方法),让main等待调度线程
      

  5.   

    1.条件一:等5个结束了main再执行
    5个subThread都join()2.条件一:5个subThread交替执行
    在五个subThread中共享同一个执行的互斥的锁不就好了?
    这种实现貌似很简单。
    如果要看代码的话,你借鉴Timer的中的任务队列中任务执行互斥的写法就好了。
      

  6.   

    循环 join 一下就可以了,或者使用 JDK 并发包(java.util.concurrent)中的 CyclicBarrier(循环障栅)或者CountDownLatch(倒计数门闩)这两个类,这两个类的 API DOC 中都有示例的。