java线程Callable Future FutureTask CompletionService

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/vmaps/article/details/80421057
public class CallableAndFuture {
    public static void main(String[] args) {
        Callable<Integer> callable = new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        };
        FutureTask<Integer> future = new FutureTask<Integer>(callable);
        new Thread(future).start();
        try {
            Thread.sleep(5000);// 可能做一些事情
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
public class CallableAndFuture {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<Integer> future = threadPool.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        });
        try {
            Thread.sleep(5000);// 可能做一些事情
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
public class CallableAndFuture {
public static void main(String[] args) {
    ExecutorService threadPool = Executors.newCachedThreadPool();
    CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
    for(int i = 1; i < 5; i++) {
        final int taskID = i;
        cs.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                return taskID;
            }
        });
    }
    // 可能做一些事情
    for(int i = 1; i < 5; i++) {
        try {
            System.out.println(cs.take().get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

}

猜你喜欢

转载自blog.csdn.net/vmaps/article/details/80421057