FutureTask源碼分析-重點方法

1.FutureTask的7中狀態轉換

​​在這裏插入圖片描述

2.重點方法分析

1.get()

在這裏插入圖片描述

/**
	 * @throws CancellationException {@inheritDoc}
	 */
	public V get() throws InterruptedException, ExecutionException {
		int s = state;
		//如果還沒執行完,則等待
		if (s <= COMPLETING)
			s = awaitDone(false, 0L);
		//通過report取結果
		return report(s);
	}

/**
	 * 等待完成或者中斷或時間結束來中斷
	 *
	 * @param timed true 如果使用了 timed 等待
	 * @param nanos 如果使用了timed,等待的時間
	 * @return 完成的狀態
	 */
	private int awaitDone(boolean timed, long nanos)
			throws InterruptedException {
		//記錄等待超時時間
		final long deadline = timed ? System.nanoTime() + nanos : 0L;
		//多個在等待結果的線程,通過一個鏈表進行保存,waitNode就是每個線程在鏈表中的節點
		WaitNode q = null;
		boolean queued = false;
		//死循環-自旋鎖同步
		for (;;) {
			//判斷當前這個調用get的線程是否被中斷
			if (Thread.interrupted()) {
				//將當前線程移出隊列
				removeWaiter(q);
				throw new InterruptedException();
			}

			int s = state;
			//如果狀態非初創或執行完畢了,跳出循環,通過report()取執行結果
			if (s > COMPLETING) {
				if (q != null)
					q.thread = null;
				return s;
			}
			//如果狀態等於已執行,讓出cpu執行,等待狀態變爲正常結束
			else if (s == COMPLETING) // cannot time out yet
				Thread.yield();
			//如果當前線程還沒有創建對象的waitNode節點,則創建一個
			else if (q == null)
				q = new WaitNode();
			//如果當前線程對應的waitNode還沒有加入等待鏈表中,則加入進去。
			else if (!queued)
				queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
						q.next = waiters, q);
			//如果有設置等待超時時間,則通過parkNanos掛起當前線程,等待繼續執行的信號
			else if (timed) {
				nanos = deadline - System.nanoTime();
				if (nanos <= 0L) {
					removeWaiter(q);
					return state;
				}
				LockSupport.parkNanos(this, nanos);
			}
			else
				//通過park掛起當前線程,等待task執行結束後給它發一個繼續執行的信號(unpark)
				LockSupport.park(this);
		}
	}

/**
	 * 任務結束後返回結果或者拋出異常
	 *
	 * @param s 完成狀態值
	 */
	@SuppressWarnings("unchecked")
	private V report(int s) throws ExecutionException {
		Object x = outcome;
		//正常結束,返回x(x是callable執行的結果outcome)
		if (s == NORMAL)
			return (V)x;
		//如果被取消,則拋出已取消異常
		if (s >= CANCELLED)
			throw new CancellationException();
		throw new ExecutionException((Throwable)x);
	}

2.run()

在這裏插入圖片描述

public void run() {
		//判斷狀態及設置futuretask歸屬的線程
		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 {
					//執行Callable
					result = c.call();
					//標記爲執行成功
					ran = true;
				} catch (Throwable ex) {
					result = null;
					//標記爲不成功
					ran = false;
					//設置爲異常狀態,並通知其他在等待結果的線程
					setException(ex);
				}
				if (ran)
					//如果執行成功,修改狀態爲正常,並通知其他在等待結果的線程
					set(result);
			}
		} finally {
			// runnner必須不爲null直到解決了阻止對run()的併發調用的狀態
			runner = null;
			//避免中斷泄漏,在runner爲null後狀態必須爲re-read
			int s = state;
			if (s >= INTERRUPTING)
				handlePossibleCancellationInterrupt(s);
		}
	}

3 cancel()

在這裏插入圖片描述

public boolean cancel(boolean mayInterruptIfRunning) {
		//判斷狀態:只有剛創建才能取消
		//mayInterruptIfRunning: 是否中斷當前正在運行這個FutureTask的線程
		if (!(state == NEW &&
				UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
						mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
			return false;
		try {
			//如果中斷當前線程,則對runner發佈interrupt信號
			if (mayInterruptIfRunning) {
				try {
					Thread t = runner;
					if (t != null)
						t.interrupt();
				} finally { // final state
					//修改狀態爲:已經通知線程中斷。
					UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
				}
			}
		} finally {
			//通知其他在等待結果的線程
			finishCompletion();
		}
		return true;
	}

3 舉例代碼

package com.xmg.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureTaskDemo {

	public static void main(String[] args) {
		System.out.println("main start");
		Callable<String>  callable = new Callable(){

			@Override
			public String call() throws Exception {
				String result = "a";
				try {
					int a = 5 / 0;
				}catch(ArithmeticException e){
					System.out.println("0");
				}
				return result;
			}
		};

		FutureTask<String> f1 = new FutureTask(callable);

		Callable<String>  callable2 = new Callable(){

			@Override
			public String call() throws Exception {
				String result = "b";
				return result;
			}
		};
		FutureTask<String> f2 = new FutureTask(callable2);

		// Callable運行在Runnable的run方法中。
		new Thread(f1).start();
		new Thread(f2).start();

		//設置f1爲取消狀態,f1.get()方法也應該註釋掉
		//f1.cancel(true);

		try {
			String result1 = f1.get();
			String result2 = f2.get();
			System.out.println(result1+result2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}


		System.out.println("main end");
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章