`

多线程并发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 有顺序的。 wait有释放锁(https://blog.csdn.net/pange1991/article/details/53860651
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就能中断线程吗。
    调用Thread.interrupt()方法并不能真正停止线程,只是在当前线程做了一个中断的状态标志
阅读jdk或spring源码正确方式。


  • 大小: 403 KB
  • 大小: 310.4 KB
  • 大小: 360.1 KB
  • 大小: 168.7 KB
  • 大小: 93.1 KB
分享到:
评论

相关推荐

    张孝祥Java多线程与并发库高级应用笔记

    - **JDK1.5线程并发库**:引入了更高级的并发控制机制,如`ExecutorService`、`Callable`、`Future`等,提供了更安全、更高效的多线程解决方案,减少了线程同步和死锁的风险。 ##### 2. 创建线程的两种传统方式 - ...

    java多线程并发编程 核心技术应用实践

    在《java多线程并发编程核心技术应用实践》中,我们将深入探讨Java平台上的并发机制、线程安全与同步控制、线程池以及实战技巧。 首先,我们需要理解Java中的线程基础。线程是程序执行的最小单位,一个进程可以有多...

    经典Java多线程与并发库高级应用

    总结来说,Java多线程与并发库的高级应用,既包括了传统的多线程编程技术,也包含了JDK 1.5之后引入的高级并发工具和特性。掌握这些知识点对于任何想要在Java编程领域深入发展的开发者来说,都是非常必要的。

    JDK源码,整合所有内容

    源码中可以看到如何实现函数式接口及其在多线程、事件处理等场景的应用。 4. **并发编程** - `java.util.concurrent`包提供了丰富的并发工具类,如`ExecutorService`、`Future`、`Semaphore`等,源码分析有助于...

    jdk源码学习

    通过深入学习JDK源码,我们不仅能理解Java平台的核心工作原理,还能提升编程技巧,学习到高级设计模式和最佳实践。同时,这也是一个不断迭代和优化的过程,因为Oracle公司和其他开源社区会定期发布新的JDK版本,引入...

    jdk源码阅读.zip

    Java并发编程是多线程环境中的基石。在JDK1.8中,`java.util.concurrent`包提供了丰富的并发工具类,如`ExecutorService`、`Future`、`Semaphore`和`CyclicBarrier`等。`ConcurrentHashMap`是并发安全的哈希映射,其...

    JDK1.6源码

    源码解析有助于掌握这些并发工具类的实现原理,从而编写更高效的多线程程序。 4. **I/O流** JDK 1.6对I/O流进行了改进,引入了NIO(Non-blocking I/O)框架,提供了一种异步数据传输方式。通过分析源码,可以学习...

    jdk1.5 线程并发与线程池的使用

    在Java编程语言中,线程并发和线程池是多任务执行的核心概念,尤其是在...熟练掌握这些工具,能帮助开发者编写出更加稳定、高效的多线程应用程序。通过深入学习和实践,可以更好地理解和利用这些特性,优化程序性能。

    汪文君高并发编程实战视频资源下载.txt

    │ 高并发编程第二阶段21讲、多线程Future设计模式详细介绍-上.mp4 │ 高并发编程第二阶段22讲、多线程Future设计模式详细介绍-下.mp4 │ 高并发编程第二阶段23讲、第二阶段课程答疑学员问题.mp4 │ 高并发编程...

    jdk1.8 sun源码

    3. **并发与多线程**:`java.util.concurrent`包提供了高级并发工具,如`ExecutorService`、`Future`、`BlockingQueue`等,这些工具的源码能帮助理解并发编程的最佳实践。 4. **JNI接口**:JNI是Java与本地代码交互...

    基于JDK的多线程归类并发处理闩工具(基于JDK1.8)

    ConcurrentLatch是一个基于JDK的多线程归类并发处理闩工具(基于JDK1.8)。与CountDownLatch不同的是它可以方便的获取哪个任务对应的哪个返回内容。与Future(或者FutureTask)不同的是,他可以通过一系列策略管理多个...

    Java-jdk10-最新最全多线程编程实战指南-核心篇

    通过阅读《Java-jdk10-最新最全多线程编程实战指南-核心篇》这本书,开发者不仅可以理解Java多线程编程的基础知识,还能掌握高级并发编程技巧,从而在实际项目中实现高性能、高并发的程序设计。对于Java开发者来说,...

    JDK源码 src

    同时,JDK源码中的并发编程组件,如`java.util.concurrent`包下的`ExecutorService`和`Future`接口,展示了Java如何处理多线程任务。源码分析能让我们掌握线程池的创建、管理和任务调度,从而在编写并发程序时更加...

    汪文君高并发编程实战视频资源全集

    │ 高并发编程第二阶段21讲、多线程Future设计模式详细介绍-上.mp4 │ 高并发编程第二阶段22讲、多线程Future设计模式详细介绍-下.mp4 │ 高并发编程第二阶段23讲、第二阶段课程答疑学员问题.mp4 │ 高并发编程...

    jdk1.6源码

    在JDK1.6源码中,我们可以看到许多经典的并发工具,如`java.util.concurrent`包,其中的线程池、Future、Semaphore等工具类为多线程编程提供了强大支持。此外,JVM内存管理、垃圾收集的实现也是源码中的重点,比如...

    jdk1.7源代码

    ExecutorService、Future、Callable接口,以及synchronized、volatile关键字的实现,都是多线程编程的重点。理解这些源码可以帮助我们编写更高效、更安全的并发代码。 5.IO流:Java的IO系统在1.7版本中已经有了丰富...

    基于JDK源码解析Java领域中的并发锁,我们需要特别关注哪些内容?

    理解和掌握这些并发锁的原理和实现,能够帮助开发者编写高效、安全的并发代码,避免常见的死锁、活锁和饥饿等问题,提升多线程环境下的程序性能。在实际开发中,应根据具体需求选择合适的锁机制,并合理使用,以实现...

    JDK源代码Java源码

    此外,JDK源码中还包括了对反射、多线程、网络通信、I/O流、集合框架等核心组件的实现。例如,`java.lang.reflect`包中的`Method`和`Constructor`类,让我们明白反射机制是如何工作的;`java.util.concurrent`包下的...

    jdk:jdk源码阅读

    4. **多线程**:深入研究Thread类和synchronized关键字,理解线程状态转换、死锁、活锁、阻塞队列等概念,以及ExecutorService和Future接口的应用,有助于开发高并发程序。 5. **网络编程**:Socket、ServerSocket...

    javajdk源码学习-JavaSourceLearn:jdk源码学习

    1. **Java基础知识**:在深入源码之前,我们需要对Java的基础语法有扎实的理解,包括类、对象、接口、异常处理、多线程、集合框架等。这些是理解源码的基础,因为源码中的每个功能都是基于这些概念构建的。 2. **...

Global site tag (gtag.js) - Google Analytics