Java线程池之WorkStealingPool,任务窃取算法

 1 import java.io.IOException;
 2 import java.util.concurrent.ExecutorService;
 3 import java.util.concurrent.Executors;
 4 import java.util.concurrent.TimeUnit;
 5 
 6 /**
 7  * 任务窃取算法
 8  */
 9 public class WorkStealingPool {
10 
11     public static void main(String[] args) {
12 
13         ExecutorService service = Executors.newWorkStealingPool();
14 
15         System.out.println(Runtime.getRuntime().availableProcessors());
16 
17         service.submit(new R(1)); //精灵线程
18         service.submit(new R(2));
19         service.submit(new R(2));
20         service.submit(new R(2));
21         service.submit(new R(2));
22 
23         try {
24             System.in.read();
25             //由于产生的是精灵线程(守护线程、后台线程),主程序不阻塞的话看不到打印信息
26         } catch (IOException e) {
27             e.printStackTrace();
28         }
29 
30     }
31 
32     static class R implements Runnable {
33 
34         int time;
35 
36         R(int runTime) {
37             this.time = runTime;
38         }
39 
40         @Override
41         public void run() {
42             try {
43                 TimeUnit.SECONDS.sleep(time);
44             } catch (InterruptedException e) {
45                 e.printStackTrace();
46             }
47             System.out.println(time + " " + Thread.currentThread().getName());
48         }
49     }
50 
51 Java线程池之WorkStealingPool,任务窃取算法

newWorkStealingPool线程池的实现用到了ForkJoinPool,用到了分而治之,递归计算的算法,
有兴趣的可以查看博客https://www.cnblogs.com/mxh-java/p/12244318.html
上一篇:详解 线程池


下一篇:webpack bug及解决方案