awaitTermination

来源:3-10 线程池状态

林就远

2020-11-24

老师,您好,想请教您个问题:
forkjoinpool线程池,为了保证线程池里的子线程优于主线程(main)先执行,只有当线程池中的子线程全部执行完再执行主线程,这里我使用awaitTermination(time,timeunit)方法。
可是,在线程池的子线程执行任务的时候,为什么main线程也会去执行任务,而不是单纯的在那等待?
图片描述

还有一个问题:
forkjoinpool线程池,在执行某个任务的时候创建了20个子线程帮助执行该任务。当该任务执行结束,那么在不关闭forkjoinpool线程池的情况下,这20个子线程会被GC回收吗?
望老师解惑,谢谢

写回答

3回答

悟空

2020-11-25

小伙伴的探索精神很好,就是因为Forkjoinpool不是new出来的,是因为ForkJoinPool pool = ForkJoinPool.commonPool();用公共线程池。这个就是公共线程池的特性,对于公共线程池来说,主线程也是可以用来执行任务的。

0
2
悟空
回复
林就远
你的3 4 ,是正常现象,线程池就应该是这样的,只不过commonPool特殊,请看commonPool方法的注释 /** * Returns the common pool instance. This pool is statically * constructed; its run state is unaffected by attempts to {@link * #shutdown} or {@link #shutdownNow}. However this pool and any * ongoing processing are automatically terminated upon program * {@link System#exit}. Any program that relies on asynchronous * task processing to complete before program termination should * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence}, * before exit. * * @return the common pool instance * @since 1.8 所以不使用commonPool即可,用我们自己的new ForkJoinPool()是最合适的。
2020-11-25
共2条回复

林就远

提问者

2020-11-24

public static void main(String[] args) throws InterruptedException {
    ForkJoinPool pool = ForkJoinPool.commonPool();
    pool.submit(new Task(0,100));
    pool.awaitTermination(1,TimeUnit.HOURS);
    System.out.println(Thread.currentThread().getName() + "【我是来捣乱的】");
}

static class Task extends RecursiveAction{

    int n;
    int front;

    Task(int front, int n){
        this.front = front;
        this.n = n;
    }

    @Override
    protected void compute() {
        if ((n - front) < 5){
            for (int i = front; i < n; i++) {
                System.out.println(Thread.currentThread().getName() + " number:" + i + " 大帅比");
            }
        }
        else {
            Task frontHalfTask = new Task(front,(front + n) /2);
            Task backHalfTask = new Task((front + n) / 2, n);
            frontHalfTask.fork();
            backHalfTask.fork();
        }
    }
}


0
0

林就远

提问者

2020-11-24

老师,我测出来是因为,我的Forkjoinpool不是new出来的,是因为ForkJoinPool pool = ForkJoinPool.commonPool();用公共线程池,可是为啥公共线程池就包含main线程呢。

0
0

深度解密Java并发工具,精通JUC,成为并发多面手

JUC全方位讲解,构建并发工具类知识体系

1599 学习 · 573 问题

查看课程