Dynamic resizing of java.util.concurrent.ThreadPoolExecutor while it has waiting tasks

前端 未结 5 476
走了就别回头了
走了就别回头了 2020-12-05 08:02

I\'m working with a java.util.concurrent.ThreadPoolExecutor to process a number of items in parallel. Although the threading itself works fine, at times we\'ve

5条回答
  •  温柔的废话
    2020-12-05 08:42

    I was in a need for the same solution too, and it seems that in JDK8 the setCorePoolSize() and setMaximumPoolSize() do indeed produce the desired result. I made a test case where I submit 4 tasks to the pool and they execute concurently, I shrink the pool size while they are running and submit yet another runnable that I want to be lonesome. Then I restore the pool back to its original size. Here is the test source https://gist.github.com/southerton81/96e141b8feede3fe0b8f88f679bef381

    It produces the following output (thread "50" is the one that should be executed in isolation)

    run:
    test thread 2 enter
    test thread 1 enter
    test thread 3 enter
    test thread 4 enter
    test thread 1 exit
    test thread 2 exit
    test thread 3 exit
    test thread 4 exit
    test thread 50 enter
    test thread 50 exit
    test thread 1 enter
    test thread 2 enter
    test thread 3 enter
    test thread 4 enter
    test thread 1 exit
    test thread 2 exit
    test thread 3 exit
    test thread 4 exit
    

提交回复
热议问题