主线程等待子线程的几种实现方式

最近遇到多线程编程里面一个常见的问题:“如何让主线程在全部子线程执行完毕后再继续执行?”。经过一番查找和实践后就整理了几种常见的实现方式

方法一:主线程sleep

主线程等待子线程执行完最简单的方式当然是在主线程中Sleep一段时间,这种方式最简单,我们先看下实现


    private static class MyThread extends Thread {

        @Override

        public void run() {

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

            System.out.println(String.format("%s %s was finished", DateUtils.format(new Date(), "hh:mm:ss:SSS"), getName()));

        }

    }

    public static void main(String[] args) {

        System.out.println(String.format("%s I was main and I'm started", DateUtils.format(new Date(), "hh:mm:ss:SSS")));

        for (int i = 0; i < 10; i++) {

            MyThread myThread = new MyThread();

            myThread.start();

        }

        try {

            Thread.sleep(3000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println(String.format("%s I was main and I'm finished", DateUtils.format(new Date(), "hh:mm:ss:SSS")));

    }

但这种方式有个非常大的弊端:无法准确地预估全部子线程执行完毕的时间。时间太久,主线程就需要空等;时间太短,子线程又可能没有全部执行完毕。

方法二:子线程join

那么另外一种方式就是使用线程的Join()方法来实现主线程的等候,我们还是先来看下实现代码

    //此处省略MyThread代码,同上
    
    public static void main(String[] args) {
        System.out.println(String.format("%s I was main and I'm started", DateUtils.format(new Date(), "hh:mm:ss:SSS")));
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            MyThread myThread = new MyThread();
            myThread.start();
            threads.add(myThread);
        }
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(String.format("%s I was main and I'm finished", DateUtils.format(new Date(), "hh:mm:ss:SSS")));
    }

可以看到我们在全部子线程开始执行后,又在主线程中执行全部子线程的join方法,那么主线程会等待全部子线程执行完毕后继续往下执行。这里放上Java 7 Concurrency Cookbook对join方法的定义,个人认为比JDK中定义更准确。

join() method suspends the execution of the calling thread until the object called finishes its execution.

我们看下join方法的源码


    public final void join() throws InterruptedException {

        join(0);

    }



    public final synchronized void join(long millis)

    throws InterruptedException {

        long base = System.currentTimeMillis();

        long now = 0;

        if (millis < 0) {

            throw new IllegalArgumentException("timeout value is negative");

        }

        if (millis == 0) {

            while (isAlive()) {

                wait(0);

            }

        } else {

            while (isAlive()) {

                long delay = millis - now;

                if (delay <= 0) {

                    break;

                }

                wait(delay);

                now = System.currentTimeMillis() - base;

            }

        }

    }

可以看到,如果join的参数为0,那么主线程会一直判断自己是否存活,如果主线程存活,则调用主线程的wait()方法,那么我们继续看下wait方法的定义


/**

    * Causes the current thread to wait until either another thread invokes the

    * {@link java.lang.Object#notify()} method or the

    * {@link java.lang.Object#notifyAll()} method for this object, or a

    * specified amount of time has elapsed.

    */

    public final native void wait(long timeout) throws InterruptedException;

大概意思是说wait(0)会使主线程进入睡眠状态,直到调用join方法的线程(简称t线程,下同)执行完毕后调用notify()或notifyAll()将其唤醒。注意这个地方有几点需要特别说明:

  1. 代码中没有显示调用notify或notifyAll的地方,这个唤醒操作其实是由于Java虚拟机在线程执行完毕后所做的

  2. 主线程需要获得t线程的对象锁(wait 意味着拿到该对象的锁),然后进入睡眠状态

  3. 由于每个子线程都执行了join方法,所以主线程需要等待全部子线程执行完毕后才能被唤醒

方法三:使用CountDownLatch

另外我们还可以使用java.util.concurrent包里的CountDownLatch,初始设置和子线程个数相同的计数器,子线程执行完毕后计数器减1,直到全部子线程执行完毕。注意countDownLatch不可能重新初始化或者修改CountDownLatch对象内部计数器的值,一个线程调用countdown方法happen-before另外一个线程调用await方法


    private static CountDownLatch latch = new CountDownLatch(10);

    public static void main(String[] args) {

        System.out.println(String.format("%s I was main and I'm started", DateUtils.format(new Date(), "hh:mm:ss:SSS")));

        for (int i = 0; i < 10; i++) {

            MyThread myThread = new MyThread();

            myThread.start();

        }

        try {

            latch.await();

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println(String.format("%s I was main and I'm finished", DateUtils.format(new Date(), "hh:mm:ss:SSS")));

    }

关于CountDownLatch的具体实现这里不再详细展开,如有兴趣可以戳这里,我们目前只需要直到await会使主线程阻塞直到计数器清零即可

方法四:使用CycleBarrier

另外还可以使用CycleBarrier实现主线程等待。CyclicBarrier 的字面意思是可循环使用(Cyclic)的屏障(Barrier)。它要做的事情是,让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续干活。CyclicBarrier默认的构造方法是CyclicBarrier(int parties),其参数表示屏障拦截的线程数量,每个线程调用await方法告诉CyclicBarrier我已经到达了屏障,然后当前线程被阻塞。

我们看下实现代码


    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(10);

    private static class MyThread extends Thread {

        @Override

        public void run() {

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

            System.out.println(String.format("%s %s was finished", DateUtils.format(new Date(), "hh:mm:ss:SSS"), getName()));

            try {

                cyclicBarrier.await();

            } catch (InterruptedException e) {

                e.printStackTrace();

            } catch (BrokenBarrierException e) {

                e.printStackTrace();

            }

        }

    }

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

        System.out.println(String.format("%s I was main and I'm started", DateUtils.format(new Date(), "hh:mm:ss:SSS")));

        for (int i = 0; i < 10; i++) {

            MyThread myThread = new MyThread();

            myThread.start();

        }

        try {

            cyclicBarrier.await();

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println(String.format("%s I was main and I'm finished", DateUtils.format(new Date(), "hh:mm:ss:SSS")));

    }

看完方法三和方法四,有人就要问了:“CountDownLatch和CyclicBarrier都能够实现线程之间的等待,这两种方式有什么区别”。别急,下面就来讲下他们的区别

  • CountDownLatch一般用于某个线程A等待若干个其他线程执行完任务之后,它才执行,而CyclicBarrier一般用于一组线程互相等待至某个状态,然后这一组线程再同时执行;

  • CountDownLatch是不能够重用的,而CyclicBarrier是可以重用的(reset)。

执行结果

由于四种方式的执行结果大同小异,我们这里就放出两种同步和异步的执行结果

同步执行结果

image

异步执行结果

image
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355

推荐阅读更多精彩内容