CompletionServiceTest.java 1012 字节
Newer Older
武汉红喜's avatar
武汉红喜 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
package org.hongxi.java.util.concurrent;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author shenhongxi 2019/8/11
 */
public class CompletionServiceTest {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(10);
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor);
武汉红喜's avatar
java  
武汉红喜 已提交
14 15

        // produce
武汉红喜's avatar
武汉红喜 已提交
16 17
        for (int i = 0; i < 10; i++) {
            final int seq = i + 1;
武汉红喜's avatar
武汉红喜 已提交
18
            completionService.submit(() -> {
武汉红喜's avatar
武汉红喜 已提交
19
                Thread.sleep(new Random().nextInt(3000));
武汉红喜's avatar
武汉红喜 已提交
20 21 22
                return seq;
            });
        }
武汉红喜's avatar
java  
武汉红喜 已提交
23 24

        // consume
武汉红喜's avatar
武汉红喜 已提交
25 26 27 28 29 30 31 32 33 34 35 36
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println(completionService.take().get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        executor.shutdown();
    }
}