记一次JAVA多线程开发

发布于 2021-01-21  734 次阅读


java future 线程池

大体思路步骤如下

  • 1)任务类实现Callable接口
  • 2)创建线程池:ExecutorService es=Executors.newCachedThreadPool();
  • 3)执行任务:Future submit = executor.submit(new ThreadTest());
  • 4)获取子线程中任务的执行结果:future.get()
//1.定义callable接口

    class ThreadTest implements Callable {

        private Integer outTime = 2000;

        ThreadTest(Integer outTime){
            this.outTime = outTime;
        }
        @Override
        public Integer call() throws Exception {
            System.out.println("开始插入数据:"+outTime);
            Thread.sleep(outTime);
            return outTime;
        }
    }
//定义请求参数和线程池

List tempList = new ArrayList<>();
tempList.add(3000);
tempList.add(2000);
tempList.add(1000);
tempList.add(3000);
tempList.add(2000);
tempList.add(1000);
tempList.add(3000);
tempList.add(2000);
tempList.add(1000);
tempList.add(3000);
//添加多线程,采用hutool的线程创建,具体可以自定义
private static ExecutorService executor = ExecutorBuilder.create()
            .setCorePoolSize(3)
            .setMaxPoolSize(10)
            .setKeepAliveTime(5000)
            .setWorkQueue(new LinkedBlockingQueue())
            .build();

//创建线程
List> futures = new ArrayList<>();
for (int i = 0 ;i< tempList.size();i++) {
   Future submit = executor.submit(new ThreadTest(tempList.get(i)));
   futures.add(submit);
}

//4.获取线程执行结果
List retList = new ArrayList<>();
for (int i = 0; i < tempList.size(); i++) {
   try {
          Integer success= futures.get(i).get();
          System.out.println(String.format(Locale.CHINA,"执行完毕,结果为%s",success));
           retList.add(success);
        } catch (InterruptedException| ExecutionException e) {
                e.printStackTrace();
        }
    }
记一次JAVA多线程开发

从上图可以看出,future接收顺序为线程存入的顺序,即先进先出,这明显不是想要的结果,因此做一下改造。

CompletionService 先完成先接收

将上述的第二第三步骤代码进行修改:


CompletionService completionService = new ExecutorCompletionService(executor);
for (int i = 0 ;i< tempList.size();i++) {
  completionService.submit(new ThreadTest(tempList.get(i)));
}
List retList = new ArrayList<>();
for (int i = 0 ;i< tempList.size();i++) {
  try {
    Integer success= completionService.take().get();
    System.out.println(String.format(Locale.CHINA,"执行完毕,结果为%s",success));
    retList.add(success);
  } catch (InterruptedException| ExecutionException e) {
    e.printStackTrace();
  }
}
记一次JAVA多线程开发

上图可以看出,先执行完毕的已经先一步接收了。

TODO:在JDK1.8中,还有一种新的future方法CompletableFuture,后续补充


Follow your heart ~!