可能是最全的java线程指南(1-3)[任务调度类_CompletionService系]

Posted by Zeusro on May 10, 2019
👈🏻 Select language
1
2
graph TB
A(CompletionService<V>)-->B(ExecutorCompletionService)

image

CompletionService

可自行实现该接口.这是一个任务队列.

取出队列元素的poll和take方法

take会阻塞知道队列出现结果

poll使用的前提是确保队列已经有结果,不然贸贸然使用会出现空指针.可以指定一个超时等待时间,避免长时间卡死.

ExecutorCompletionService

一般都是声明CompletionService<V>,实例化ExecutorCompletionService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    int TOTAL_TASK = 2;

    public void run() throws InterruptedException, ExecutionException {
        // 创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(TOTAL_TASK);
        CompletionService<Integer> cService = new ExecutorCompletionService<>(pool);

        // 向里面扔任务
        for (int i = 0; i < TOTAL_TASK; i++) {
            cService.submit(new CallableExample());
            //重载的这个submit(Runnable task, V result)方法,是自行把结果传入
        }
        // 检查线程池任务执行结果
        for (int i = 0; i < TOTAL_TASK; i++) {
            Future<Integer> future = cService.take();
            System.out.println("method:" + future.get());
        }
        // 关闭线程池
        pool.shutdown();
    }

其他例子

1
2
graph TB
A(CompletionService<V>)-->B(ExecutorCompletionService)

image

CompletionService

You can implement this interface yourself. This is a task queue.

poll and take methods for retrieving queue elements.

take will block until a result appears in the queue.

poll should be used on the premise that the queue already has results, otherwise using it rashly will cause null pointer. You can specify a timeout wait time to avoid long blocking.

ExecutorCompletionService

Generally declare CompletionService<V>, instantiate ExecutorCompletionService.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    int TOTAL_TASK = 2;

    public void run() throws InterruptedException, ExecutionException {
        // Create thread pool
        ExecutorService pool = Executors.newFixedThreadPool(TOTAL_TASK);
        CompletionService<Integer> cService = new ExecutorCompletionService<>(pool);

        // Throw tasks into it
        for (int i = 0; i < TOTAL_TASK; i++) {
            cService.submit(new CallableExample());
            //This overloaded submit(Runnable task, V result) method passes the result in yourself
        }
        // Check thread pool task execution results
        for (int i = 0; i < TOTAL_TASK; i++) {
            Future<Integer> future = cService.take();
            System.out.println("method:" + future.get());
        }
        // Shutdown thread pool
        pool.shutdown();
    }

Other Examples

1
2
graph TB
A(CompletionService<V>)-->B(ExecutorCompletionService)

image

CompletionService

Вы можете реализовать этот интерфейс самостоятельно. Это очередь задач.

Методы poll и take для извлечения элементов очереди.

take будет блокировать до появления результата в очереди.

poll следует использовать при условии, что очередь уже имеет результаты, иначе опрометчивое использование вызовет нулевой указатель. Вы можете указать время ожидания таймаута, чтобы избежать длительной блокировки.

ExecutorCompletionService

Обычно объявляют CompletionService<V>, создают экземпляр ExecutorCompletionService.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    int TOTAL_TASK = 2;

    public void run() throws InterruptedException, ExecutionException {
        // Создать пул потоков
        ExecutorService pool = Executors.newFixedThreadPool(TOTAL_TASK);
        CompletionService<Integer> cService = new ExecutorCompletionService<>(pool);

        // Бросить задачи в него
        for (int i = 0; i < TOTAL_TASK; i++) {
            cService.submit(new CallableExample());
            //Этот перегруженный метод submit(Runnable task, V result) передает результат сам
        }
        // Проверить результаты выполнения задач пула потоков
        for (int i = 0; i < TOTAL_TASK; i++) {
            Future<Integer> future = cService.take();
            System.out.println("method:" + future.get());
        }
        // Завершить работу пула потоков
        pool.shutdown();
    }

Другие примеры



💬 讨论 / Discussion

对这篇文章有想法?欢迎在 GitHub 上发起讨论。
Have thoughts on this post? Start a discussion on GitHub.

在 GitHub 参与讨论 / Discuss on GitHub