码迷,mamicode.com
首页 > 编程语言 > 详细

Java线程Callable_Future_Executors线程池的使用

时间:2016-02-18 11:41:14      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!