Thread Join介绍【java多线程】

JOIN介绍

   1为什么要用join?

    比如,需要同时异步执行2个任务,任务执行需要的时间不一定相同,此时主线程暂停,等待2个任务都处理完了,主线程做后续任务。还要说的再详细点不?给我留言,我再解释。 

   1、JDK说明

public final void join()
                throws InterruptedException
Waits for this thread to die.
An invocation of this method behaves in exactly the same way as the invocation
join(0)
Throws:
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

 

   2、demo

import java.util.Random;

public class ThreadJoinTest {

    public static void main(String[] args) {

        Thread t1 = new Thread(new MyThread());
        Thread t2 = new Thread(new MyThread());
        Thread t3 = new Thread(new MyThread());
        Thread t4 = new Thread(new MyThread());
        Thread t5 = new Thread(new MyThread());

        try {
            t1.start();
            t2.start();
            t3.start();
            t4.start();
            t5.start();

            t1.join();
            t2.join();
            t3.join();
            t4.join();
            t5.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("子线程都跑完啦,轮到哥收尾了。");
    }
}

class MyThread implements Runnable {

    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000 * (new Random()).nextInt(5));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":" + i + "次执行!");
        }
        System.out.println(Thread.currentThread().getName() + "结束了。");
    }
}

猜你喜欢

转载自xuhuanblog.iteye.com/blog/2409764