欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java ThreadPoolExecutor 并发调用实例详解

程序员文章站 2024-02-17 10:28:10
java threadpoolexecutor 并发调用实例详解 概述 通常为了提供任务的处理速度,会使用一些并发模型,threadpoolexecutor中的in...

java threadpoolexecutor 并发调用实例详解

概述

通常为了提供任务的处理速度,会使用一些并发模型,threadpoolexecutor中的invokeall便是一种。

代码

package test.current;

import java.util.arraylist;
import java.util.arrays;
import java.util.list;
import java.util.concurrent.callable;
import java.util.concurrent.executionexception;
import java.util.concurrent.future;

public class testcallable {

  public static void main(string[] args) throws interruptedexception, executionexception {

    list<callable<list<long>>> tasks = new arraylist<>();
    for (int i = 0; i < 10; i++) {
      callable<list<long>> task = new callable<list<long>>() {
        @override
        public list<long> call() throws exception {
          return arrays.aslist(1l,2l);
        }
      };

      tasks.add(task);
    }

    list<long> finalresults = new arraylist<>(10);
    list<future<list<long>>> results = threadpool.getthreadpool().invokeall(tasks);
    for(future<list<long>> ele : results) {
      list<long> list = ele.get();
      finalresults.addall(list);
    }

    system.out.println(finalresults);
  }
}

package test.current;

import java.util.concurrent.arrayblockingqueue;
import java.util.concurrent.threadpoolexecutor;
import java.util.concurrent.timeunit;

public class threadpool {
  private static final int core_size = 8;

  private static final int max_size = 12;

  private static final long keep_alive_time = 30;

  private static final int queue_size = 50000;

  private static threadpoolexecutor threadpool = new threadpoolexecutor(core_size, max_size, keep_alive_time,
      timeunit.seconds, new arrayblockingqueue<runnable>(queue_size), new threadpoolexecutor.abortpolicy());

  public static threadpoolexecutor getthreadpool() {
    return threadpool;
  }
}

可以把需要执行的任务创建一个callable task,利用线程池中的线程并发的执行这些task,从而提高任务的执行效率。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!