利用join方法,让多个线程有序执行

和wait()有点类似,join()方法可以让多个线程之间排队等待,按照一定的顺序执行。join方法是阻塞的,会一直等到取消或超时为止。假如现在有三个线程,main,t0,t1,要在main线程启动之后相继执行t0,t1,那么可以在main线程之后,启动t0,t0加入执行队列,即t0.join(),之后再启动t1,t1.join()。


public class JoinDemo {

      public static void main(String args[]) throws InterruptedException{

            System.out.println(Thread.currentThread().getName() + " is Started");

            Thread t0 = new Thread(){
                public void run(){
                    try {
                        System.out.println(Thread.currentThread().getName() + " is Started,sleep 2 second");
                        Thread.sleep(2000);
                        System.out.println(Thread.currentThread().getName() + " is Completed");
                    } catch (InterruptedException ex) {
                    }
                }
            };

            t0.start();
            t0.join();


            Thread t1 = new Thread(){
                public void run(){
                    try {
                        System.out.println(Thread.currentThread().getName() + " is Started,sleep 6 second");
                        Thread.sleep(6000);
                        System.out.println(Thread.currentThread().getName() + " is Completed");
                    } catch (InterruptedException ex) {
                    }
                }
            };

            t1.start();
            t1.join();

            System.out.println(Thread.currentThread().getName() + " is Completed");
        }

}

执行结果:

main is Started
Thread-0 is Started,sleep 2 second
Thread-0 is Completed
Thread-1 is Started,sleep 6 second
Thread-1 is Completed
main is Completed

你可能感兴趣的:(java多线程编程,线程按照顺序执行)