# 异步多任务执行

  • 支持执行子任务
  • 支持配置线程池
  • 获取线程信息
List<Future<Object>> works = new ArrayList<> ();
        ExecutorService executor = ExecutorBuilder.create ()
                .setCorePoolSize (1)
                .setMaxPoolSize (1)
                .setKeepAliveTime (0)
                .build ();
        CompletionService<Object> objectCompletionService = ThreadUtil.newCompletionService (executor);
        works.add (objectCompletionService.submit (new Runnable () {
            @Override
            public void run () {
                System.out.println ("ab");
            }
        }, "ab1"));
        works.add (objectCompletionService.submit (new Runnable () {
            @Override
            public void run () {
                System.out.println ("ab12");
                try {
                    Thread.sleep (30000);
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
            }
        }, "ab11"));
        //获取信息,异步等待
        works.forEach (item -> {
            try {
                System.out.println (item.get ());
            } catch (InterruptedException e) {
                e.printStackTrace ();
            } catch (ExecutionException e) {
                e.printStackTrace ();
            }
        });

        //线程结束操作
         executor.shutdown ();
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

# 多线程等待

public class ThreadUtilTest {
    /**
     * 多线程实现线程等待的功能,所有线程的任务都指向完成后主线程才可以往下走
     * @throws InterruptedException
     */
    public static void test1() throws InterruptedException {
        CountDownLatch countDownLatch=ThreadUtil.newCountDownLatch(5);
        for(int i=0;i<5;i++){
            ThreadUtil.execute(() -> {
                try {
                    Thread.sleep(6000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第个线程");
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println("完成");

    }
    public static void main(String[] args) throws InterruptedException {
        test1();
    }
}
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