awaitTermination
来源:3-10 线程池状态

林就远
2020-11-24
老师,您好,想请教您个问题:
forkjoinpool线程池,为了保证线程池里的子线程优于主线程(main)先执行,只有当线程池中的子线程全部执行完再执行主线程,这里我使用awaitTermination(time,timeunit)方法。
可是,在线程池的子线程执行任务的时候,为什么main线程也会去执行任务,而不是单纯的在那等待?
还有一个问题:
forkjoinpool线程池,在执行某个任务的时候创建了20个子线程帮助执行该任务。当该任务执行结束,那么在不关闭forkjoinpool线程池的情况下,这20个子线程会被GC回收吗?
望老师解惑,谢谢
写回答
3回答
-
小伙伴的探索精神很好,就是因为Forkjoinpool不是new出来的,是因为ForkJoinPool pool = ForkJoinPool.commonPool();用公共线程池。这个就是公共线程池的特性,对于公共线程池来说,主线程也是可以用来执行任务的。
022020-11-25 -
林就远
提问者
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(); } } }
00 -
林就远
提问者
2020-11-24
老师,我测出来是因为,我的Forkjoinpool不是new出来的,是因为ForkJoinPool pool = ForkJoinPool.commonPool();用公共线程池,可是为啥公共线程池就包含main线程呢。
00