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");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值