问题:java主线程等待子线程执行完毕后再执行

来源:互联网 发布:淘宝如何鉴定质量问题 编辑:程序博客网 时间:2024/06/10 01:29

工作总往往会遇到异步去执行某段逻辑, 然后先处理其他事情, 处理完后再把那段逻辑的处理结果进行汇总的场景, 这时候就需要使用线程了.

  一个线程启动之后, 是异步的去执行需要执行的内容的, 不会影响主线程的流程,  往往需要让主线程指定后, 等待子线程的完成. 这里有几种方式.

  站在主线程的角度, 我们可以分为主动式被动式.

  主动式指主线程主动去检测某个标志位, 判断子线程是否已经完成. 被动式指主线程被动的等待子线程的结束, 很明显, 比较符合人们的胃口. 就是你事情做完了, 你告诉我, 我汇总一下, 哈哈.

1.      JoinDemo(主动式)

目的:等待当前线程的die

示例:

复制代码
package com.test; public class JoinDemo {    public static void main(String[] args) throws Exception {        //创建子线程,并启动子线程        Thread subThread = new Thread(new SubThread());        subThread.start();        //主线程处理其他工作,让子线程异步去执行        mainWork();        //主线程其他工作完毕,等待子线程的结束, 调用join系列的方法即可(可以设置超时时间)        subThread.join();        System.out.println("Now all thread done!");    }    private static void mainWork() throws Exception{        System.out.println("Main thread start work!");        //sleep        Thread.sleep(2000L);        System.out.println("Main Thread work done!");    }    /**     * 子线程类     * @author fuhg     */    private static class SubThread implements Runnable{        public void run() {            // TODO Auto-generated method stub            System.out.println("Sub thread is starting!");            try {                Thread.sleep(5000L);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            System.out.println("Sub thread is stopping!");        }    }}
复制代码

 

2.      FutureDemo

  使用并发包下面的Future模式.

  Future是一个任务执行的结果, 他是一个将来时, 即一个任务执行, 立即异步返回一个Future对象, 等到任务结束的时候, 会把值返回给这个future对象里面. 我们可以使用    ExecutorService接口来提交一个线程.(注意:Future.get()为一个阻塞方法)

  示例:

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.test;
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
public class FutureDemo {
    //创建一个容量为1的线程池
    static ExecutorService executorService = Executors.newFixedThreadPool(1);
     
    public static void main(String[] args) throws Exception {
        //创建线程并提交线程,同时获取一个future对象
        Thread subThread = new Thread(new SubThread());
        Future future = executorService.submit(subThread);
        //主线程处理其他工作,让子线程异步去执行
        mainWork();
        //阻塞,等待子线程结束
        future.get();
        System.out.println("Now all thread done!");
        //关闭线程池
        executorService.shutdown();
    }
    //主线程工作
    private static void mainWork(){
        System.out.println("Main thread start work!");
        try {
            Thread.sleep(2000L);
        catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Main Thread work done!");
    }
    /**
     * 子线程类
     * @author fuhg
     */
    private static class SubThread implements Runnable{
        public void run() {
            // TODO Auto-generated method stub
            System.out.println("Sub thread is starting!");
            try {
                Thread.sleep(5000L);
            catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Sub thread is stopping!");
        }
    }
}

 

3.      CountDownDemo

  上面两种情况在线程数为一两个的时候,还可以,如果需要控制的线程数很多的话,再采取这种方式就有点过意不去了。

  第一种方法, 你要调用很多个线程的join, 特别是当你的线程不是for循环创建的, 而是一个一个创建的时候.

  第二种方法, 要调用很多的future的get方法, 同第一种方法.

 

  所以去Concurrent库里面找找看还有什么东东吧。

  CountDownLanch 是一个倒数计数器, 给一个初始值(>=0), 然后每一次调用countDown就会减1, 这很符合等待多个子线程结束的场景: 一个线程结束的时候, countDown一次, 直到所有的线程都countDown了 , 那么所有子线程就都结束了.

  先看看CountDownLanch提供的方法吧

  

  

  await: 会阻塞等待计数器减少到0位置. 带参数的await是多了等待时间.

  countDown: 将当前的计数减1

  getCount(): 返回当前的计数

  显而易见, 我们只需要在子线程执行之前, 赋予初始化countDownLanch, 并赋予线程数量为初始值.

  每个线程执行完毕的时候, 就countDown一下.主线程只需要调用await方法, 可以等待所有子线程执行结束。

  示例:

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.test;
 
import java.util.concurrent.CountDownLatch;
 
public class CountDownDemo {
 
    public static void main(String[] args) throws Exception {
        //定义线程数
        int subThreadNum = 5;
        //取得一个倒计时器,从5开始
        CountDownLatch countDownLatch = new CountDownLatch(subThreadNum);
        //依次创建5个线程,并启动
        for (int i = 0; i < subThreadNum; i++) {
            new SubThread(2000*(i+1), countDownLatch).start();
        }
        //主线程工作
        mainWork();
        //等待所有的子线程结束
        countDownLatch.await();
        System.out.println("Main Thread work done!");
    }
    private static void mainWork(){
        System.out.println("Main thread start work!");
        try {
            Thread.sleep(2000L);
        catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Main Thread work done!");
    }
    /**
     * 子线程类
     * @author fuhg
     */
    private static class SubThread extends Thread{
         
        private CountDownLatch countDownLatch;
        private long workTime;
         
        public SubThread(long workTime,CountDownLatch countDownLatch){
            this.workTime = workTime;
            this.countDownLatch = countDownLatch;
        }
         
        public void run() {
            // TODO Auto-generated method stub
            try {
                System.out.println("Sub thread is starting!");
                Thread.sleep(workTime);
                System.out.println("Sub thread is stopping!");
            catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            finally {
                //线程结束时,将计时器减一
                countDownLatch.countDown();
            }
        }
    }
}
阅读全文
0 0