标签:
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线程池的使用
标签:
原文地址:http://www.cnblogs.com/chenyaqiang/p/5197551.html