多线程并发Future模式应用以及jdk源码分析

多线程三种方式:
http://blog.csdn.net/aboy123/article/details/38307539
runnable与callable区别:
https://www.cnblogs.com/frinder6/p/5507082.html

callable与futurTask实现:
package com.hailong.hailongTest.thread;

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

import com.hailong.hailongTest.InsertSort;
import com.hailong.hailongTest.SelectSort;

public class UserServiceByFuture {
	
	public static Map<String, String> UserServiceByFuture(final int[] testInts1, final int[] testInts2) {
		
//		InsertSort insertSort = new InsertSort();
//		SelectSort selectSort = new SelectSort();
//		Map<String, String> result = new HashMap<String, String>();
//		result.put("a", insertSort.getInsertSort(testInts1));
//		result.put("b", selectSort.getSelectSort(testInts2));
		
		//-----------------------------------------------------------
		Callable<String> callableString = new Callable<String>() {

			public String call() throws Exception {
				
				InsertSort insertSort = new InsertSort();
				return insertSort.getInsertSort(testInts1);
				// TODO Auto-generated method stub
			}
		};
		
		FutureTask<String> futureTask = new FutureTask<String>(callableString);
		new Thread(futureTask).start();
		//-----------------------------------------------------------
		Callable<String> callableString2 = new Callable<String>() {

			public String call() throws Exception {
				
				SelectSort selectSort = new SelectSort();
				return selectSort.getSelectSort(testInts2);
				// TODO Auto-generated method stub
			}
		};
		
		FutureTask<String> futureTask2 = new FutureTask<String>(callableString2);
		new Thread(futureTask2).start();
		//-----------------------------------------------------------
		Map<String, String> result = new HashMap<String, String>();
		try {
			result.put("a", futureTask.get());
			result.put("b", futureTask2.get());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}
	
	public static void main(String[] args) {
		long currentTime = System.currentTimeMillis();
		int[] testInts1 = {1,44,6,2,45,98,45};
		int[] testInts2 = {1,44,6,2,45,98,45};
		// TODO Auto-generated method stub
		Map<String, String> result = UserServiceByFuture(testInts1, testInts2);
		
		System.out.println(result.get("a"));
		System.out.println(result.get("b"));
		System.out.println(System.currentTimeMillis() - currentTime);
	}

}


get()怎样实现阻塞。
执行完之后,如何通知其他线程的。



futureTask的run:
https://www.jianshu.com/p/7ef8be1205ec




futureTask源码分析:
import java.util.concurrent.FutureTask.WaitNode;
import java.util.concurrent.locks.LockSupport;

public class FutureTask<V> implements RunnableFuture<V> {

    /**
     * The run state of this task, initially NEW.  The run state
     * transitions to a terminal state only in methods set,
     * setException, and cancel.  During completion, state may take on
     * transient values of COMPLETING (while outcome is being set) or
     * INTERRUPTING (only while interrupting the runner to satisfy a
     * cancel(true)). Transitions from these intermediate to final
     * states use cheaper ordered/lazy writes because values are unique
     * and cannot be further modified.
     *
     * 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;

    /** The underlying callable; nulled out after running */
    private Callable<V> callable;
    /** The result to return or exception to throw from get() */
    private Object outcome; // non-volatile, protected by state reads/writes
    /** The thread running the callable; CASed during run() */
    private volatile Thread runner;
    /** Treiber stack of waiting threads */
    private volatile WaitNode waiters;

    /**
     * Returns result or throws exception for completed task.
     *
     * @param s completed state value
     */
    @SuppressWarnings("unchecked")
    private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
    }

    /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Callable}.
     *
     * @param  callable the callable task
     * @throws NullPointerException if the callable is null
     */
    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

    /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Runnable}, and arrange that {@code get} will return the
     * given result on successful completion.
     *
     * @param runnable the runnable task
     * @param result the result to return on successful completion. If
     * you don't need a particular result, consider using
     * constructions of the form:
     * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
     * @throws NullPointerException if the runnable is null
     */
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

    public boolean isCancelled() {
        return state >= CANCELLED;
    }

    public boolean isDone() {
        return state != NEW;
    }

    // 只能取消还没被执行的任务(任务状态为NEW的任务)- cancel(boolean)
    public boolean cancel(boolean mayInterruptIfRunning) {
    	// 只有刚创建的情况才能取消
        if (state != NEW)
            return false;
        // ture:中断,false:取消
        if (mayInterruptIfRunning) {
        	// 继续判断任务的当前状态是否为NEW,因为此时执行任务线程可能再度获得处理了,任务状态可能已发生改变
            if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
                return false;
            // 如果任务状态依然是NEW, 也就是执行线程没有改变任务的状态, 
            // 则让执行线程中断(在这个过程中执行线程可能会改变任务的状态)
            Thread t = runner;
            // 对runner 发布interrupt信号
            if (t != null)
                t.interrupt();
            // 修改状态为已经通知线程中断
            UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
        }
        else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
            return false;
        finishCompletion();
        return true;
    }

    /**
     * @throws CancellationException {@inheritDoc}
     * 获取任务的执行结果-get()方法和get(long,TimeUnit)方法, 核心在于内部调用的awaitDone()方法
     */
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

    /**
     * @throws CancellationException {@inheritDoc}
     */
    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }


    /**
     * Sets the result of this future to the given value unless
     * this future has already been set or has been cancelled.
     *
     * <p>This method is invoked internally by the {@link #run} method
     * upon successful completion of the computation.
     *
     * @param v the value
     */
    protected void set(V v) {
    	// 首先将任务的状态改变
        // 状态改变成功之后再将结果赋值
        // 赋值成功,改变任务的状态
        // 处理等待线程队列(将线程阻塞状态改为唤醒,这样哪些等待获取结果的线程就可以取得任务结果)
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            // 修改状态
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            // 通知其他在等待结果的线程
            finishCompletion();
        }
    }

    /**
     * Causes this future to report an {@link ExecutionException}
     * with the given throwable as its cause, unless this future has
     * already been set or has been cancelled.
     *
     * <p>This method is invoked internally by the {@link #run} method
     * upon failure of the computation.
     *
     * @param t the cause of failure
     */
    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            // 修改为异常状态
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            // 通知其他在等待结果的线程
            finishCompletion();
        }
    }

    public void run() {
    	// 判断状态来设置futuretask归属线程
    	// 1.判断任务的状态是否是初始化状态
    	// 2.判断执行任务的线程对象runner是否为空,为空就将当前执行线程赋值给runner属性
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
         // 任务状态是NEW, 并且callable不为空(在任务被cancel()时,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)
            	// 如果状态为发起中断信号(INTERRUPTING = 5)或已经中断信号(INTERRUPTED  = 6)
            	// 让出cpu()
                handlePossibleCancellationInterrupt(s);
        }
    }

    /**
     * Executes the computation without setting its result, and then
     * resets this future to initial state, failing to do so if the
     * computation encounters an exception or is cancelled.  This is
     * designed for use with tasks that intrinsically execute more
     * than once.
     *
     * @return true if successfully run and reset
     */
    protected boolean runAndReset() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return false;
        boolean ran = false;
        int s = state;
        try {
            Callable<V> c = callable;
            if (c != null && s == NEW) {
                try {
                    c.call(); // don't set result
                    ran = true;
                } catch (Throwable ex) {
                    setException(ex);
                }
            }
        } 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
            s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        return ran && s == NEW;
    }

    /**
     * Removes and signals all waiting threads, invokes done(), and
     * nulls out callable.
     * 在任务执行完成(包括取消、正常结束、发生异常), 将等待线程列表唤醒
     * 同时让任务执行体置空
     */
    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
    }

    /**
     * Awaits completion or aborts on interrupt or timeout.
     *
     * @param timed true if use timed waits
     * @param nanos time to wait, if timed
     * @return state upon completion
     * 等待任务的执行结果
     * timed: 是否有时间限制  nanos: 限制的时间
     */
    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 (;;) {
        	// 判断当前线程是否被中断
            if (Thread.interrupted()) {
            	// 当前线程移出队列
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;

            // 1. 首先判断任务状态是否是完成状态, 如果完成, 是就直接返回结果
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            // 2. 如果1为false,并且任务的状态是COMPLETING(已执行,但没有结束), 也就是在set()任务结果时被阻塞了,则让出当前线程cpu资源
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            // 3. 如果前两步false,并且q==null,则初始化一个当前线程的等待节点
            else if (q == null)
                q = new WaitNode();
			// 4. 下一次循环体, 如果前3步依然是false,并且当前节点没有加入到等待列表,
			//    则将当前线程节点放在等待列表的第一个位置
            // 如果当前线程对应的WaitNode还没有加入到等待链表中,就加进去
            else if (!queued)
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            // 5. 在下一次循环, 如果前4步为false, 如果是时间范围内等待的,则判断当前时间是否过期,
            //  过期则将线程节点移出等待队列并返回任务状态结果, 如果没过期,则让当前线程阻塞一定时间
            // 通过parkNanos挂起当前线程,等待继续执行信号。
            else if (timed) {
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                LockSupport.parkNanos(this, nanos);
            }
            // 6. 如果不是时间范围内等待, 并且前5步均为false,则让线程阻塞,直到被唤醒
            // 通过pack挂起当前线程,等待task run执行结束发送执行信号(unpack)
            else
                LockSupport.park(this);
        }
    }

    /**
     * Tries to unlink a timed-out or interrupted wait node to avoid
     * accumulating garbage.  Internal nodes are simply unspliced
     * without CAS since it is harmless if they are traversed anyway
     * by releasers.  To avoid effects of unsplicing from already
     * removed nodes, the list is retraversed in case of an apparent
     * race.  This is slow when there are a lot of nodes, but we don't
     * expect lists to be long enough to outweigh higher-overhead
     * schemes.
     * 将线程节点从等待队列中移出
     */
    private void removeWaiter(WaitNode node) {
        if (node != null) {
            node.thread = null;
            retry:
            for (;;) {          // restart on removeWaiter race
                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                    s = q.next;
                    if (q.thread != null)
                        pred = q;
                    else if (pred != null) {
                        pred.next = s;
                        if (pred.thread == null) // check for race
                            continue retry;
                    }
                    else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                          q, s))
                        continue retry;
                }
                break;
            }
        }
    }

}


wait/notify 有顺序的。
park/unpark挂起线程,一次性的,与先后顺序无关。灵活
park(a);
unpark(a);

ExecutorService对象原理简析:
http://blog.csdn.net/lu123535884/article/details/49495833
线程池 submit execute区别
http://blog.csdn.net/u010940300/article/details/50251841

感想思考:
线程状态有哪些,如何变化的。
调用了interrupt就能中断线程吗。
阅读jdk或spring源码正确方式。


猜你喜欢

转载自572327713.iteye.com/blog/2406904