Skip to content

Commit 01442a9

Browse files
committed
updates
1 parent 8903c0a commit 01442a9

7 files changed

Lines changed: 427 additions & 5 deletions

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
* [volatile关键字解析](https://alleniverson.gitbooks.io/java-basic-introduction/content/第5章%20多线程/volatile关键字解析.html)
5656
* [HandlerThread](https://alleniverson.gitbooks.io/java-basic-introduction/content/第5章%20多线程/HandlerThread.html)
5757
* [Callable和Future](https://alleniverson.gitbooks.io/java-basic-introduction/content/第5章%20多线程/Callable和Future.html)
58+
* [Java中的Runnable、Callable、Future、FutureTask的区别与示例](第5章 多线程/Java中的Runnable、Callable、Future、FutureTask的区别与示例.md)
5859
* [Java程序死锁问题原理及解决方案](https://alleniverson.gitbooks.io/java-basic-introduction/content/第5章%20多线程/Java程序死锁问题原理及解决方案.html)
5960
* [线程锁技术](https://alleniverson.gitbooks.io/java-basic-introduction/content/第5章%20多线程/线程锁技术.html)
6061
* [定时器、互斥、同步通信技术](https://alleniverson.gitbooks.io/java-basic-introduction/content/第5章%20多线程/定时器、互斥、同步通信技术.html)

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
* [volatile关键字解析](第5章 多线程/volatile关键字解析.md)
4949
* [HandlerThread](第5章 多线程/HandlerThread.md)
5050
* [Callable和Future](第5章 多线程/Callable和Future.md)
51+
* [Java中的Runnable、Callable、Future、FutureTask的区别与示例](第5章 多线程/Java中的Runnable、Callable、Future、FutureTask的区别与示例.md)
5152
* [Java程序死锁问题原理及解决方案](第5章 多线程/Java程序死锁问题原理及解决方案.md)
5253
* [线程锁技术](第5章 多线程/线程锁技术.md)
5354
* [定时器、互斥、同步通信技术](第5章 多线程/定时器、互斥、同步通信技术.md)
Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
> 原文链接:Mr.Simple,http://blog.csdn.net/bboyfeiyu/article/details/24851847
2+
3+
Java中存在Runnable、Callable、Future、FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别。
4+
5+
## Runnable
6+
其中Runnable应该是我们最熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值。然后使用某个线程去执行该runnable即可实现多线程,Thread类在调用start()函数后就是执行的是Runnable的run()函数。Runnable的声明如下 :
7+
```java
8+
public interface Runnable {
9+
/**
10+
* When an object implementing interface <code>Runnable</code> is used
11+
* to create a thread, starting the thread causes the object's
12+
* <code>run</code> method to be called in that separately executing
13+
* thread.
14+
* <p>
15+
*
16+
* @see java.lang.Thread#run()
17+
*/
18+
public abstract void run();
19+
}
20+
```
21+
## Callable
22+
Callable与Runnable的功能大致相似,Callable中有一个call()函数,但是call()函数有返回值,而Runnable的run()函数不能将结果返回给客户程序。Callable的声明如下 :
23+
```java
24+
public interface Callable<V> {
25+
/**
26+
* Computes a result, or throws an exception if unable to do so.
27+
*
28+
* @return computed result
29+
* @throws Exception if unable to compute a result
30+
*/
31+
V call() throws Exception;
32+
}
33+
```
34+
可以看到,这是一个泛型接口,call()函数返回的类型就是客户程序传递进来的V类型。
35+
## Future
36+
Executor就是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果、设置结果操作。get方法会阻塞,直到任务返回结果(Future简介)。Future声明如下 :
37+
```java
38+
/**
39+
* @see FutureTask
40+
* @see Executor
41+
* @since 1.5
42+
* @author Doug Lea
43+
* @param <V> The result type returned by this Future's <tt>get</tt> method
44+
*/
45+
public interface Future<V> {
46+
47+
/**
48+
* Attempts to cancel execution of this task. This attempt will
49+
* fail if the task has already completed, has already been cancelled,
50+
* or could not be cancelled for some other reason. If successful,
51+
* and this task has not started when <tt>cancel</tt> is called,
52+
* this task should never run. If the task has already started,
53+
* then the <tt>mayInterruptIfRunning</tt> parameter determines
54+
* whether the thread executing this task should be interrupted in
55+
* an attempt to stop the task. *
56+
*/
57+
boolean cancel(boolean mayInterruptIfRunning);
58+
59+
/**
60+
* Returns <tt>true</tt> if this task was cancelled before it completed
61+
* normally.
62+
*/
63+
boolean isCancelled();
64+
65+
/**
66+
* Returns <tt>true</tt> if this task completed.
67+
*
68+
*/
69+
boolean isDone();
70+
71+
/**
72+
* Waits if necessary for the computation to complete, and then
73+
* retrieves its result.
74+
*
75+
* @return the computed result
76+
*/
77+
V get() throws InterruptedException, ExecutionException;
78+
79+
/**
80+
* Waits if necessary for at most the given time for the computation
81+
* to complete, and then retrieves its result, if available.
82+
*
83+
* @param timeout the maximum time to wait
84+
* @param unit the time unit of the timeout argument
85+
* @return the computed result
86+
*/
87+
V get(long timeout, TimeUnit unit)
88+
throws InterruptedException, ExecutionException, TimeoutException;
89+
}
90+
```
91+
## FutureTask
92+
FutureTask则是一个RunnableFuture&lt;V>,而RunnableFuture实现了Runnbale又实现了Futrue&lt;V>这两个接口,
93+
```java
94+
public class FutureTask<V> implements RunnableFuture<V>
95+
```
96+
RunnableFuture
97+
```java
98+
public interface RunnableFuture<V> extends Runnable, Future<V> {
99+
/**
100+
* Sets this Future to the result of its computation
101+
* unless it has been cancelled.
102+
*/
103+
void run();
104+
}
105+
```
106+
另外它还可以包装Runnable和Callable&lt;V>, 由构造函数注入依赖。
107+
```java
108+
public FutureTask(Callable<V> callable) {
109+
if (callable == null)
110+
throw new NullPointerException();
111+
this.callable = callable;
112+
this.state = NEW; // ensure visibility of callable
113+
}
114+
115+
public FutureTask(Runnable runnable, V result) {
116+
this.callable = Executors.callable(runnable, result);
117+
this.state = NEW; // ensure visibility of callable
118+
}
119+
```
120+
可以看到,Runnable注入会被Executors.callable()函数转换为Callable类型,即FutureTask最终都是执行Callable类型的任务。该适配函数的实现如下 :
121+
```java
122+
public static <T> Callable<T> callable(Runnable task, T result) {
123+
if (task == null)
124+
throw new NullPointerException();
125+
return new RunnableAdapter<T>(task, result);
126+
}
127+
```
128+
RunnableAdapter适配器
129+
```java
130+
/**
131+
* A callable that runs given task and returns given result
132+
*/
133+
static final class RunnableAdapter<T> implements Callable<T> {
134+
final Runnable task;
135+
final T result;
136+
RunnableAdapter(Runnable task, T result) {
137+
this.task = task;
138+
this.result = result;
139+
}
140+
public T call() {
141+
task.run();
142+
return result;
143+
}
144+
}
145+
```
146+
由于FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。并且还可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。因此FutureTask既是Future、Runnable,又是包装了Callable( 如果是Runnable最终也会被转换为Callable ), 它是这两者的合体。
147+
148+
简单示例
149+
150+
```java
151+
package com.effective.java.concurrent.task;
152+
153+
import java.util.concurrent.Callable;
154+
import java.util.concurrent.ExecutionException;
155+
import java.util.concurrent.ExecutorService;
156+
import java.util.concurrent.Executors;
157+
import java.util.concurrent.Future;
158+
import java.util.concurrent.FutureTask;
159+
160+
/**
161+
*
162+
* @author mrsimple
163+
*
164+
*/
165+
public class RunnableFutureTask {
166+
167+
/**
168+
* ExecutorService
169+
*/
170+
static ExecutorService mExecutor = Executors.newSingleThreadExecutor();
171+
172+
/**
173+
*
174+
* @param args
175+
*/
176+
public static void main(String[] args) {
177+
runnableDemo();
178+
futureDemo();
179+
}
180+
181+
/**
182+
* runnable, 无返回值
183+
*/
184+
static void runnableDemo() {
185+
186+
new Thread(new Runnable() {
187+
188+
@Override
189+
public void run() {
190+
System.out.println("runnable demo : " + fibc(20));
191+
}
192+
}).start();
193+
}
194+
195+
/**
196+
* 其中Runnable实现的是void run()方法,无返回值;Callable实现的是 V
197+
* call()方法,并且可以返回执行结果。其中Runnable可以提交给Thread来包装下
198+
* ,直接启动一个线程来执行,而Callable则一般都是提交给ExecuteService来执行。
199+
*/
200+
static void futureDemo() {
201+
try {
202+
/**
203+
* 提交runnable则没有返回值, future没有数据
204+
*/
205+
Future<?> result = mExecutor.submit(new Runnable() {
206+
207+
@Override
208+
public void run() {
209+
fibc(20);
210+
}
211+
});
212+
213+
System.out.println("future result from runnable : " + result.get());
214+
215+
/**
216+
* 提交Callable, 有返回值, future中能够获取返回值
217+
*/
218+
Future<Integer> result2 = mExecutor.submit(new Callable<Integer>() {
219+
@Override
220+
public Integer call() throws Exception {
221+
return fibc(20);
222+
}
223+
});
224+
225+
System.out
226+
.println("future result from callable : " + result2.get());
227+
228+
/**
229+
* FutureTask则是一个RunnableFuture<V>,即实现了Runnbale又实现了Futrue<V>这两个接口,
230+
* 另外它还可以包装Runnable(实际上会转换为Callable)和Callable
231+
* <V>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行
232+
* ,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。
233+
*/
234+
FutureTask<Integer> futureTask = new FutureTask<Integer>(
235+
new Callable<Integer>() {
236+
@Override
237+
public Integer call() throws Exception {
238+
return fibc(20);
239+
}
240+
});
241+
// 提交futureTask
242+
mExecutor.submit(futureTask) ;
243+
System.out.println("future result from futureTask : "
244+
+ futureTask.get());
245+
246+
} catch (InterruptedException e) {
247+
e.printStackTrace();
248+
} catch (ExecutionException e) {
249+
e.printStackTrace();
250+
}
251+
}
252+
253+
/**
254+
* 效率底下的斐波那契数列, 耗时的操作
255+
*
256+
* @param num
257+
* @return
258+
*/
259+
static int fibc(int num) {
260+
if (num == 0) {
261+
return 0;
262+
}
263+
if (num == 1) {
264+
return 1;
265+
}
266+
return fibc(num - 1) + fibc(num - 2);
267+
}
268+
269+
}
270+
```
271+
输出结果
272+
273+
![](http://img.blog.csdn.net/20140501233308453?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYmJveWZlaXl1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)

第5章 多线程/同步工具类.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -708,6 +708,8 @@ public class BlockingQueueCommunication {
708708

709709
### **ConcurrentHashMap**
710710

711+
使用锁分段技术
712+
711713
同步的HashMap,支持获取的完全并发和更新的所期望可调整并发的哈希表。此类遵守与 Hashtable 相同的功能规范,并且包括对应于 Hashtable 的每个方法的方法版本。
712714

713715
不过,尽管所有操作都是线程安全的,但获取操作不 必锁定,并且不 支持以某种防止所有访问的方式锁定整个表。此类可以通过程序完全与 Hashtable 进行互操作,这取决于其线程安全,而与其同步细节无关。

第5章 多线程/多线程.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@
2525

2626
多线程的存在,不是提高程序的执行速度。其实是为了提高应用程序的使用率。程序的执行其实都是在抢CPU的资源,CPU的执行权。多个进程是在抢这个资源,而其中的某一个进程如果执行路径比较多,就会有更高的几率抢到CPU的执行权。我们是不敢保证哪一个线程能够在哪个时刻抢到,所以线程的执行有随机性。
2727

28-
### **1.2.5 什么是并行、并发呢?**
28+
### 1.2.5 线程与进程的关系
29+
30+
线程是CPU调度的最小单元,同时线程是一种有限的系统资源,即线程不可能无限制地产生,并且线程的创建和销毁都有相应的开销。而进程一般指一个执行单元,在PC和移动设备上指一个程序或者一个应用。一个进程可以包含多个线程,因此进程和线程是包含与被包含的关系。
31+
32+
### **1.2.6 什么是并行、并发呢?**
2933

3034
前者是逻辑上同时发生,指在某一个时间内同时运行多个程序;后者是物理上同时发生,指在某一个时间点同时运行多个程序。那么,我们能不能实现真正意义上的并发呢?答案是可以的,多个CPU就可以实现,不过你得知道如何调度和控制它们。
3135

第5章 多线程/线程池.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ public ThreadPoolExecutor(
6161

6262
### **2.1.5 RejectedExecutionHandler**
6363

64+
当线程池和workQueue都满了的情况下,对新加任务采取的处理策略也有几个默认的实现,分别如下
65+
6466
- ThreadPoolExecutor.AbortPolicy
6567
当添加任务出错时的策略捕获器,丢弃任务并抛出RejectedExecutionException异常
6668

@@ -71,7 +73,7 @@ public ThreadPoolExecutor(
7173
丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
7274

7375
- ThreadPoolExecutor.CallerRunsPolicy
74-
由调用线程处理该任务
76+
拒绝新任务进入,如果该线程池还没有被关闭,那么由调用线程处理该任务
7577

7678
# **3. 任务提交给线程池之后的处理策略**
7779
3.1 如果当前线程池中的线程数目小于corePoolSize,则每来一个任务,就会创建执行这个任务
@@ -104,8 +106,10 @@ public ThreadPoolExecutor(
104106
| BlockingDeque | 双端队列 |
105107
| SynchronousQueue | 同步队列,无界队列,直接提交策略,交替队列,在某次添加元素后必须等待其他线程取走后才能继续添加 |
106108
| LinkedBlockingQueue | 无界队列,基于链表的阻塞队列,可以并发运行,FIFO |
109+
| LinkedBlockingDueue | 双向链表实现的双向并发阻塞队列。同时支持FIFO和FILO两种操作方式,即可以从队列的头和尾同时操作(插入/删除),并且该阻塞队列是支持线程安全的。 |
110+
| ConcurrentLinkedQueue | 基于链接节点的无界线程安全队列 |
107111
| ArrayBlockingQueue | 基于数组的有界(固定大小的数组)阻塞队列,只有put方法和take方法才具有阻塞功能,公平性 fairness |
108-
| PriorityBlockingQueue | 基于优先级的阻塞队列,依据对象的自然排序顺序或者是构造函数所带的Comparator决定的顺序 |
112+
| PriorityBlockingQueue | 基于优先级的阻塞队列,依据对象的自然排序顺序或者是构造函数所带的Comparator决定的顺序,Volley中的请求队列使用了优先级队列 |
109113
| DelayQueue | 延时队列 |
110114

111115
## 4.2 排队策略

0 commit comments

Comments
 (0)