目錄
實作callable接口(無傳回值)
建立FutureTask執行個體(無傳回值)
運作測試(無傳回值)
實作callable接口(有傳回值)
建立FutureTask執行個體(有傳回值)
運作測試(有傳回值)
探究一下futureTask
多線程使用方式---實作callable接口
實作callable接口(無傳回值)
package my.notes;
import java.util.concurrent.Callable;
public class MyCallable implements Callable {
@Override
public Object call() throws Exception {
System.out.println("實作callable");
return null;
}
}
建立FutureTask執行個體(無傳回值)
package my.notes;
import java.util.concurrent.FutureTask;
public class MyTest {
public static void main(String[] args) {
System.out.println("主線程開始執行");
MyCallable myCallable = new MyCallable();
FutureTask futureTask = new FutureTask(myCallable);
futureTask.run();
System.out.println("主線程執行完畢");
}
}
運作測試(無傳回值)
實作callable接口(有傳回值)
package my.notes;
import java.util.concurrent.Callable;
public class MyCallable implements Callable {
@Override
public Object call() throws Exception {
System.out.println("實作callable");
return "這是一個傳回值曉得吧?";
}
}
建立FutureTask執行個體(有傳回值)
package my.notes;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MyTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("主線程開始執行");
MyCallable myCallable = new MyCallable();
FutureTask futureTask = new FutureTask(myCallable);
futureTask.run();
System.out.println("callable傳回值:" + futureTask.get());
System.out.println("主線程執行完畢");
}
}
運作測試(有傳回值)
探究一下futureTask
public class FutureTask<V> implements RunnableFuture<V>
構造方法:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
來看一眼我們用到的.get方法,畢竟有一個猜測,如果那邊線程沒執行完,我們去get,會怎麼辦
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
嗯哼?發現了一個什麼,等待,哦~ get不到它會等待,阻塞嘛這不是
都到這兒了,我們繼續往下看這個等待是幹嘛的
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
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);
}
}
Lock,這下就明白了
但是也不態光一直等待啊,有等待肯定就必須有喚醒,繼續往下
public void run() {
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 {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
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;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
可以看到有一個boolean ran,是一個狀态,當我們的callable執行完傳回結果,會執行一個set,還把傳回值傳過去了,我們看看這個set
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
又調用了一個finishCompletion,那我們繼續
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);
}
這個時候是不是注意到了最後一個return了?于是我們就拿到了傳回值