Skip to content

Commit 87009c4

Browse files
committed
线程池详解
1 parent 3bfa563 commit 87009c4

File tree

15 files changed

+515
-164
lines changed

15 files changed

+515
-164
lines changed

code/java/ThreadPoolExecutorDemo/.idea/uiDesigner.xml

Lines changed: 124 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package callable;
2+
3+
import java.util.ArrayList;
4+
import java.util.Date;
5+
import java.util.List;
6+
import java.util.concurrent.ArrayBlockingQueue;
7+
import java.util.concurrent.Callable;
8+
import java.util.concurrent.ExecutionException;
9+
import java.util.concurrent.Future;
10+
import java.util.concurrent.ThreadPoolExecutor;
11+
import java.util.concurrent.TimeUnit;
12+
13+
import static common.ThreadPoolConstants.CORE_POOL_SIZE;
14+
import static common.ThreadPoolConstants.KEEP_ALIVE_TIME;
15+
import static common.ThreadPoolConstants.MAX_POOL_SIZE;
16+
import static common.ThreadPoolConstants.QUEUE_CAPACITY;
17+
18+
public class CallableDemo {
19+
public static void main(String[] args) {
20+
//使用阿里巴巴推荐的创建线程池的方式
21+
//通过ThreadPoolExecutor构造函数自定义参数创建
22+
ThreadPoolExecutor executor = new ThreadPoolExecutor(
23+
CORE_POOL_SIZE,
24+
MAX_POOL_SIZE,
25+
KEEP_ALIVE_TIME,
26+
TimeUnit.SECONDS,
27+
new ArrayBlockingQueue<>(QUEUE_CAPACITY),
28+
new ThreadPoolExecutor.CallerRunsPolicy());
29+
30+
List<Future<String>> futureList = new ArrayList<>();
31+
Callable<String> callable = new MyCallable();
32+
for (int i = 0; i < 10; i++) {
33+
//提交任务到线程池
34+
Future<String> future = executor.submit(callable);
35+
//将返回值 future 添加到 list,我们可以通过 future 获得 执行 Callable 得到的返回值
36+
futureList.add(future);
37+
}
38+
for (Future<String> fut : futureList) {
39+
try {
40+
System.out.println(new Date() + "::" + fut.get());
41+
} catch (InterruptedException | ExecutionException e) {
42+
e.printStackTrace();
43+
}
44+
}
45+
//关闭线程池
46+
executor.shutdown();
47+
}
48+
}
49+
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package callable;
2+
3+
import java.util.concurrent.Callable;
4+
5+
public class MyCallable implements Callable<String> {
6+
7+
@Override
8+
public String call() throws Exception {
9+
Thread.sleep(1000);
10+
//返回执行当前 Callable 的线程名字
11+
return Thread.currentThread().getName();
12+
}
13+
}

0 commit comments

Comments
 (0)