Skip to content

Commit 059c5b9

Browse files
committed
Create 创建线程的几种方式总结.md
1 parent 2f6380d commit 059c5b9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
## 面试官:“创建线程有哪几种常见的方式?”
2+
3+
1. 继承 Thread 类
4+
2. 实现 Runnable 接口
5+
3. 使用 Executor 框架
6+
4. 使用 FutureTask
7+
8+
## 最简单的两种方式
9+
10+
### 1.继承 Thread 类
11+
12+
13+
14+
15+
16+
### 2.实现 Runnable 接口
17+
18+
## 比较实用的两种方式
19+
20+
### 3.使用 Executor 框架
21+
22+
Executor 框架是 Java5 之后引进的,在 Java 5 之后,通过 Executor 来启动线程比使用 Thread 的 start 方法更好,除了更易管理,效率更好(用线程池实现,节约开销)外,还有关键的一点:有助于避免 this 逃逸问题。
23+
24+
> 补充:this 逃逸是指在构造函数返回之前其他线程就持有该对象的引用. 调用尚未构造完全的对象的方法可能引发令人疑惑的错误。
25+
26+
Executor 框架不仅包括了线程池的管理,还提供了线程工厂、队列以及拒绝策略等,Executor 框架让并发编程变得更加简单。
27+
28+
为了能搞懂如何使用 Executor 框架创建
29+
30+
### Executor 框架结构(主要由三大部分组成)
31+
32+
#### 1) 任务(`Runnable` /`Callable`)
33+
34+
执行任务需要实现的 **`Runnable` 接口****`Callable`接口****`Runnable` 接口****`Callable` 接口** 实现类都可以被 **`ThreadPoolExecutor`****`ScheduledThreadPoolExecutor`** 执行。
35+
36+
#### 2) 任务的执行(`Executor`)
37+
38+
如下图所示,包括任务执行机制的核心接口 **`Executor`** ,以及继承自 `Executor` 接口的 **`ExecutorService` 接口。`ThreadPoolExecutor`****`ScheduledThreadPoolExecutor`** 这两个关键类实现了 **ExecutorService 接口**
39+
40+
### 4.使用 FutureTask

0 commit comments

Comments
 (0)