Skip to content

Commit 9520927

Browse files
committed
Callable接口通过FutureTask包装器
1 parent 54c102a commit 9520927

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

thread/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@
8585

8686
- [x] [继承Thread类创建线程](src/main/java/com/cpucode/java/application/thread/MyThread.java)
8787
- [x] [实现Runnable接口创建线程](src/main/java/com/cpucode/java/application/thread/MyRunnable.java)
88+
- [x] [Callable接口通过FutureTask包装器](src/main/java/com/cpucode/java/application/thread/CallableDemo.java)
8889

8990

9091
- [返回文件目录](#文件目录)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.cpucode.java.application.thread;
2+
3+
import java.util.concurrent.*;
4+
5+
/**
6+
* 实现 Callable 接口通过 FutureTask 包装器来创建 Thread 线程
7+
*
8+
* @author : cpucode
9+
* @date : 2021/7/23
10+
* @time : 22:41
11+
* @github : https://github.com/CPU-Code
12+
* @csdn : https://blog.csdn.net/qq_44226094
13+
*/
14+
public class CallableDemo implements Callable<String> {
15+
public static void main(String[] args) throws ExecutionException, InterruptedException {
16+
ExecutorService executorService = Executors.newFixedThreadPool(1);
17+
18+
CallableDemo callableDemo = new CallableDemo();
19+
Future<String> future = executorService.submit(callableDemo);
20+
21+
System.out.println(future.get());
22+
executorService.shutdown();
23+
}
24+
25+
@Override
26+
public String call() throws Exception {
27+
int a = 1;
28+
int b = 2;
29+
30+
System.out.println(a + b);
31+
32+
return "执行结果:" + (a + b);
33+
}
34+
}

0 commit comments

Comments
 (0)