1.Future解決了什麼問題
Future是java中的一個接口,主要用於java多線程計算過程的異步結果獲取,能夠感知計算的進度,與傳統的多線程實現方式,比如繼承Thread類,實現runnable接口,它們主要的侷限在於對多線程運行的本身缺少監督。
2.Callable接口和Runnable接口區別
下面是它們之間的主要區別:
- runable接口是用run方法作爲線程運行任務的入口,callable接口使用call方法
- call方法拋出異常,run方法不拋出異常,也就是說實現callable接口,可以對線程運行任務時的出錯拋出的異常進行捕獲,從而得知任務異常的原因
- 運行Callable任務可拿到一個Future對象, Future表示異步計算的結果
- callable的實現類FutureTask提供了檢查計算是否完成的方法,以等待計算的完成,並檢索計算的結果。
3.java實現線程的三種方式:
繼承Thread類
class MyThread extends Thread{
private String str;
public MyThread(String str){
this.str = str;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.str+"="+i);
}
}
}
public class Test {
public static void main(String[] args) {
new MyThread("線程一").start();
new MyThread("線程二").start();
new MyThread("線程三").start();
}
}
實現Runnable接口
public MyRunnable implements Runnable{
public void run(){
for(int i = 0;i<100;i++){
System.out.println(i);
}
}
}
public class MyRunnableDemo{
public static void main(String[] args){
MyRunnable my = new MyRunnable();
Thread t1 = new Thread(my,”線程1”);
Thread t2 = new Thread(my,”線程2”);
t1.start();
t2.start();
}
}
實現Callable接口
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyThread implements Callable<String>{
private String title;
public MyThread(String title){
this.title = title;
}
public String call()throws Exception{
for (int i = 0; i < 10; i++) {
System.out.println(title+"i="+i);
}
return "線程執行完畢";
}
}
public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> task1 = new FutureTask<>(new MyThread("線程一"));
FutureTask<String> task2 = new FutureTask<>(new MyThread("線程二"));
new Thread(task1).start();
new Thread(task2).start();
System.out.println("線程返回數據一"+ task1.get());
System.out.println("線程返回數據二"+ task2.get());
}
}
三種實現方式都能夠達到多線程運算的目的,但是適用場景卻不同。
繼承Thread類實現多線程是最爲簡潔的方式,但是由於Java是單繼承,繼承了Thread類就不能繼承其他的類,影響了類的擴展性。
實現Runnable接口是爲了規避ava單繼承的問題,
實現Callable接口則是爲了滿足獲取異步計算結果,對線程計算更爲可控設計的。
4.實現callable接口如何使異步計算更爲可控?
通常爲了達到多線程併發運行任務,需要利用Java的Thread類,要麼繼承它,要麼傳遞一個Runnable對象給Thread類,然後通過調用它的start方法,運行異步計算任務。那麼實現callable的接口如何利用Thread類來達到多線程併發運行的目的呢?
答案是FutureTask,FutureTask類:包裝callable接口,並同時實現了Runable接口和Future接口,實現Runnable接口是爲了滿足多線程併發執行的目的,實現Future接口則是爲了滿足多線程併發過程中新線程不可控問題。
FutureTask的構造方法:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
從上面可以看出FutureTask類將Callable接口作爲自己的私有成員變量,作爲操作的起點。
而state則是FutureTask封裝的callable實現類的call方法的狀態變量,主要是瞭解異步任務的狀態
它主要定義了6種狀態,
* Possible state transitions:
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
*/
private volatile int state;
private static final int NEW = 0;
private static final int COMPLETING = 1;
private static final int NORMAL = 2;
private static final int EXCEPTIONAL = 3;
private static final int CANCELLED = 4;
private static final int INTERRUPTING = 5;
private static final int INTERRUPTED = 6;
根據它的命名可以很清楚的明白,各個常量所代表的含義。
NEW代表異步計算還沒開始,
COMPLETING 代表計算正在進行中
NORMAL 代表計算正常結束
EXCEPTIONAL 代表計算過程中出現了異常
CANCELLED 代表計算任務被取消
INTERRUPTING 代表計算任務正在被中斷執行
INTERRUPTED 代表計算任務已經被中斷執行
接着來看,FutureTask的run方法實現:
public void run() {
1。判斷計算狀態,如果不爲NEW,結束
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
//2 .執行實現Callable類的call方法
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
//3. 異常捕捉
setException(ex);
}
if (ran)
//4. 結果回顯
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
//5. 解決中斷
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
從FutureTask的run方法,可以看出,它是在以自己作爲新線程的入口,執行傳遞給自己的callable實現類的call方法,並將call方法的返回值保存在自己的私有成員變量中。
在上面代碼3處,主要是做了異常封裝的工作。
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
outcome被設計爲Object類型,這樣它既可以接受異步計算的結果,又可以接受一個Exception異常,
finishCompletion();方法,主要是爲了喚醒因調用get方法阻塞的線程。
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null; // to reduce footprint
}
最後來看最爲重要的get方法實現:
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
FutureTask主要用state變量來了解實現callable類的call方法計算的狀態,當計算狀態爲開始NEW或者正在計算COMPLETING,那麼需要考慮阻塞當前線程。阻塞是用awaitDown方法實現的。
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
1. 在get阻塞中設置線程的interrupt標誌位,可以使其跳出等待
if (Thread.interrupted()) {
2.將線程的waitor從等待鏈表中移除
removeWaiter(q);
throw new InterruptedException();
}
3.如果進入方法後查看state,發現state已經大於計算中,則可以退出等待返回結果
int s = state;
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
4. 如果快計算完,降低線程優先級,降低獲取CPU可能性
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
q = new WaitNode();
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else 阻塞線程
LockSupport.park(this);
}
}