Future和FutureTask使用案例和源码剖析[base jdk8]

Future

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by Administrator on 2018/2/2.
 *
 */
public class FutureTest {

    public static final void main(String... args) throws Exception {

        ExecutorService executorService = Executors.newCachedThreadPool();
        Future future = executorService.submit(new Callable() {
            @Override
            public Object call() throws Exception {
                Long start = System.currentTimeMillis();
                while (true) {
                    Thread.sleep(500);
                    Long current = System.currentTimeMillis();
                    if ((current - start) > 5000) {
                        return 1;
                    }
                }
            }
        });

        try {
            /**
             * 线程没有返回时会阻塞
             */
            Integer result = (Integer)future.get();
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}Future接口较简单,共提供了5个方法: 
   
  

Future和FutureTask使用案例和源码剖析[base jdk8]_第1张图片

FutureTask

/**
 * Created by Administrator on 2018/2/2.
 */
public class FutureTaskTest {

    public static final void main(String... args) throws Exception {

        ExecutorService executor = Executors.newCachedThreadPool();

        /**
         * 新建任务
         */
        Task task = new Task();
        /**
         * 包装任务
         */
         FutureTask futureTask = new FutureTask(task);

        /**
         * 提交任务
         */
         executor.submit(futureTask);
        /**
         * shutdown() 方法拒绝新任务,但终止前允许执行以前提交的任务;
         * shutdownNow() 方法拒绝新任务并试图停止当前正执行的task,并返回尚未执行的task的list
         */
         executor.shutdown();

        /**
         * 调用isDone()判断任务是否结束
         */
        if(!futureTask.isDone()) {
            System.out.println("Task is not done");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int result = 0;
        try {

            /**
             * 调用get()方法获取任务结果,如果任务没有执行完成则阻塞等待
             */
            result = futureTask.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("result is " + result);
    }

    /**
     * 继承Callable接口,实现call()方法,泛型参数为要返回的类型
     */
    static class Task  implements Callable {

        @Override
        public Integer call() throws Exception {
            System.out.println("Thread [" + Thread.currentThread().getName() + "] is running");
            int result = 0;
            for(int i = 0; i < 100;++i) {
                result += i;
            }

            Thread.sleep(3000);
            return result;
        }
    }
}
FutureTask是实体类,内部由state维护了7种Future状态

private volatile int state; #通过volatile和UNSAFE CAS实现对状态的安全高效更新

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;

    FutureTask 阻塞方法get()源码剖析

step1:内部调用了awaitDone()
 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

step2: 通过死循环 自旋和通过LockSupport.park挂起线程实现 阻塞
    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);
        }
    }

LockSupport.park()是native方法,底层基于Posix的mutex,condition来实现,实际上是一种CAS实现



你可能感兴趣的:(JAVA,网络通信-多线程)