保持主线程执行,直到执行另一个线程

时间:2016-01-12 05:27:50

标签: java

package Pack3;

public class Test4 {

    public static void main(String[] args) {

        final Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                    System.out.println("Main Thread Started !!");

                try {
                    synchronized (this) {
                        System.out.println("Waiting Mode ");
                        this.wait();
                        System.out.println("Main thread exited");
                    }
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }

            }
        });

        t.start();

        Thread[] t1 = new Thread[10];
        for (int i = 0; i < 10; i++) {
            t1[i] = new Thread(new Runnable() {

                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "Executed");
                }
            });

            if (i == 9) {

                synchronized (t1[i]) {
                    t1[i].notifyAll();
                    t1[i].start();
                }

            } else {
                t1[i].start();
            }
        }
    }

}

输出是:

Main Thread Started !!
Waiting Mode 
Thread-1Executed
Thread-2Executed
Thread-4Executed
Thread-3Executed
Thread-6Executed
Thread-7Executed
Thread-5Executed
Thread-8Executed
Thread-9Executed
Thread-10Executed

但是t(主线程)没有退出?为什么呢?

0 个答案:

没有答案