Java多线程并行处理任务的实现

Java多线程并行处理任务的实现

在实际项目开发的过程中,遇到过需要处理一个由多个子任务组成的任务的问题.顺序处理起来会造成响应时间超长,用户体验不好的问题.我想到一个解决方案,即使用多线程并行处理子任务.思路就是使用ThreadPoolExecutor线程池,然后使用一个list保存所有线程的实例引用.以下是代码实现.

以下是代码实现

FactorialCalculator 类:用于实现具体的业务处理

package ThreadTask;

import java.util.concurrent.Callable;

public class FactorialCalculator implements Callable {
    private int number;

    public FactorialCalculator(int number) {
        this.number = number;
    }

    //计算阶乘
    public Integer call() throws Exception {
        Integer result = 1;
        if (number == 0 || number == 1)
            result = 1;
        else {
            for (int i = 2; i <= number; i++) {
                result *= i;
                //为了演示效果,休眠20ms
                Thread.sleep(20);
            }
        }
        System.out.printf("线程:%s," + number + "!= %d\n", Thread.currentThread().getName(), result);
        return result;
    }

}

Main 类:用于实现多线程任务的实现和处理

import ThreadTask.FactorialCalculator;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;


public class Main {

    public static void main(String[] args) {
        Long startTime = System.currentTimeMillis();
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);//创建只有2个线程的线程池
        //存放结果的列表
        List> resultList = new ArrayList<>();
        //通过Random类生成一个随机数生成器
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int number = random.nextInt(10);
            FactorialCalculator calculator = new FactorialCalculator(number);
            Future result = executor.submit(calculator);
            resultList.add(result);
        }
        //创建一个循环来监控执行器的状态
        try {
            while (executor.getCompletedTaskCount() < resultList.size()) {
                System.out.printf("\n已完成的线程数量: %d\n", executor.getCompletedTaskCount());
                for (int i = 0; i < resultList.size(); i++) {
                    Future result = resultList.get(i);
                    System.out.printf("第 %d 个线程 : 是否完成:%s\n", i, result.isDone());
                }
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("全部线程执行结束");
        try {
            for (int i = 0; i < resultList.size(); i++) {
                Future result = resultList.get(i);
                Integer number = null;
                number = result.get();
                System.out.printf("第 %d 个线程 执行结果是: %d\n", i, number);
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        executor.shutdown();
        Long endTime = System.currentTimeMillis();
        System.out.println("使用时间 = [" + (endTime - startTime) + "]");
    }
}

你可能感兴趣的:(Java)