Skip to content

Commit 7d63a2b

Browse files
committed
newWorkStealingPool
1 parent b3f4e6d commit 7d63a2b

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

Multithread/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,5 @@ DelayQueue(执行定时任务)
4040
- newCachedThreadPool(带有缓存线程池,默认空闲线程60s)
4141
- newSingleThreadExecutor(单个线程)
4242
- newScheduledThreadPoold(定时线程池)
43+
- newWorkStealingPool(空闲线程去抢占其他线程的任务队列的任务)
4344
-

Multithread/src/T28.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
* @program JavaBooks
8+
* @description: 第五种,WorkStealingPool
9+
* @author: mf
10+
* @create: 2020/01/01 15:05
11+
*/
12+
13+
14+
public class T28 {
15+
public static void main(String[] args) throws IOException {
16+
// 默认核数
17+
ExecutorService service = Executors.newWorkStealingPool();
18+
19+
service.execute(new R(1000));
20+
service.execute(new R(2000));
21+
service.execute(new R(2000));
22+
service.execute(new R(2000));
23+
service.execute(new R(2000));
24+
25+
// 由于产生的是精灵线程(守护线程、后台线程),主线程如果不阻塞的话,看不到输出
26+
System.in.read();
27+
28+
service.shutdown();
29+
}
30+
31+
private static class R implements Runnable {
32+
33+
int time;
34+
35+
public R(int time) {
36+
this.time = time;
37+
}
38+
39+
@Override
40+
public void run() {
41+
try {
42+
TimeUnit.MILLISECONDS.sleep(time);
43+
} catch (InterruptedException e) {
44+
e.printStackTrace();
45+
}
46+
System.out.println(Thread.currentThread().getName());
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)