目前知道可以实现线程按照顺序的java原生方法有 join(),CountDownLatch,Executors.newSingleThreadExecutor(),FutureTask..

Future Clalback配合使用

package com.juc.threadpool;

import java.util.concurrent.*;

/**
 * Created by Administrator on 2018/6/28.
 */
public class FutureCallBack {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Callable<Integer> callable = () -> {
            TimeUnit.MILLISECONDS.sleep(3000);
            return 3;
        };

        FutureTask futureTask = new FutureTask(callable);
        FutureTask futureTask2 = new FutureTask(new MyTask());
        new Thread(futureTask).start();

        System.out.println(futureTask.get());//阻塞
        System.out.println("ssssssssssssssssssssss");
        new Thread(futureTask2).start();
        System.out.println(futureTask2.get());//阻塞
        System.out.println("ssssssssssssssssssssss");
        if(futureTask.isDone()){
            new Thread(futureTask2).start();
        }
        System.out.println(futureTask2.get());//阻塞


        //线程池使用
        ExecutorService executorService = Executors.newSingleThreadExecutor();
         executorService.submit(futureTask);
        System.out.println(futureTask.get());
        executorService.shutdown();
    }

    static class MyTask implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            Thread.sleep(1000);
            return 1;
        }
    }

}

 

posted on 2018-06-28 22:03  爱不死  阅读(408)  评论(0编辑  收藏  举报