Java线程Callable_Future_Executors线程池的使用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java线程Callable_Future_Executors线程池的使用相关的知识,希望对你有一定的参考价值。
1.首先创建任务
package com.currentPro.task; import java.util.concurrent.Callable; public class MuniusTask implements Callable<Integer>{ private Integer number; public MuniusTask (Integer number){ this.number = number; } @Override public Integer call() throws Exception { int result ; result = number - 1; return result; } }
2.创建TaskExecutor
public class MuniusTaskExecutor { protected ExecutorService executors; //初始化线程池 public MuniusTaskExecutor(Integer threadNums){ this.executors = Executors.newFixedThreadPool(threadNums); } }
3.测试
package com.currentPro.task; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class TaskTest { public static void main(String[] args) throws InterruptedException, ExecutionException { PlusTaskExecutor plusTaskExecutor = new PlusTaskExecutor(10); List<Future<Integer>> resultList = new ArrayList<Future<Integer>> (); Random random = new Random(); for (int i = 0; i < 4; i++) { Integer number = random.nextInt(10); System.out.println("random值:" + number); MuniusTask m1 = new MuniusTask(number); Future<Integer> result = plusTaskExecutor.executors.submit(m1); resultList.add(result); } for (Future<Integer> future : resultList) { System.out.println("Future result is - " + " - " + future.get() + "; And Task done is " + future.isDone()); } } }
4.结果
random值:2 random值:0 random值:2 random值:8 Future result is - - 1; And Task done is true Future result is - - -1; And Task done is true Future result is - - 1; And Task done is true Future result is - - 7; And Task done is true
以上是关于Java线程Callable_Future_Executors线程池的使用的主要内容,如果未能解决你的问题,请参考以下文章