Multithreading way to create a thread pool, Future and CompletableFuture

Hello everyone, I am a duck:

     Today talk about several ways to create and use multiple threads.

1. Thread 和 Runnable


    Thread class inheritance and implement Runnable.
    This example is not a child.

2. Thread Pool


  Now there are five kinds of thread pool.

  //缓存线程池
  ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); 
  //固定大小线程池
  ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
  //单线程执行
  ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
  //定时或延迟执行
  ExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);
  //窃取线程池
  ExecutorService workStealingPool = Executors.newWorkStealingPool();

Which newWorkStealingPool is a new jdk after 1.8, in order to prevent excessive thread pool enabled, cpu usage due to excessive downtime projects. Adapted to perform multiple tasks and each task takes less time.
  The remaining four ways are likely to take up the project cpu caused by excessive downtime occurs.
  4-core 16G machine, for example, the thread pool size created Executors.newFixedThreadPool (10) in this way was 10 .
  Executors.newWorkStealingPool () creates a thread pool size is four. In general, the number of nuclear and equal .
  Even without this way, it is recommended not to exceed the number of nuclear * 2. (See the specific requirements)


3. Future和CompletableFuture


Future is emerged after jdk1.5, asynchronous multi-threading.
example:

// 创建Future集合,用于存放完成的Future
List<Future<Long>> futureList = new ArrayList();
//多线程执行任务
for (int i = 0; i < 100; i++) {
    Future<Long> testFuture= workStealingPool.submit(new Callable<Long>() {
        @Override
        public Long call() {
            //模拟执行耗时任务
            System.out.println("task 1 doing...");
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0L;
        }
    });
    futureList.add(testFuture);
}
//遍历list,获取线程结果
for (Future<Long> taskResponseFuture: futureList) {
    if(taskResponseFuture.get().equals(0L)){
        //当前future执行完毕
    }
}

Here note, Future.get () is a blocking method . If you need to perform multi-threaded operation, execute get () method in the last time.
Examples of similar top and to be put into the list of the plurality of Future, recycled get.

CompletableFuture is the Future of the implementation class, on asynchronous multi-threading provides more api, here are some commonly used.


supplyAsync asynchronous execution, there is a return value

CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
  //模拟执行耗时任务
  System.out.println("task 1 doing...");
  try {
      Thread.sleep(1000);
  } catch (Exception e) {
      e.printStackTrace();
  }
  //返回结果
  return 0;
});

thenAccept output stage receiving as an input at this stage. Multithreading (single thread) execution sequence.

completableFuture1.thenApply(new Function<Integer, Object>() {
    @Override
    public Object apply(Integer integer) {
        //模拟执行耗时任务
        System.out.println("task thenApply doing...");
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
});

whenComplete asynchronous monitor results

completableFuture1.whenComplete(new BiConsumer<Integer,Throwable>() {
    @Override
    public void accept(Integer o, Throwable o2) {
        if(o == 0L){
            System.out.println("task complete...");
        }else{
            throw new RuntimeException();
        }
    }
});

 

Published 115 original articles · won praise 58 · Views 230,000 +

Guess you like

Origin blog.csdn.net/Angry_Mills/article/details/88624776