编程语言
首页 > 编程语言> > java批量多线程计算

java批量多线程计算

作者:互联网

1、需求

把计算分批交给多个不同子线程进行暂时异步并发计算,最终主线程汇总计算结果。

2、示例代码

package javabasic.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class CallableWaitDemo {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        Integer num = 10;
        List<FutureTask<Integer>> list = new ArrayList<>(num);
        for (int i = 1; i <= num; i++) {
            FutureTask<Integer> task = new FutureTask(new MyCallable(String.valueOf(i),1000, i));
            //new Thread(task).start();
            threadPool.submit(task);
            list.add(task);
        }

        Integer sum = 0;
        for (FutureTask<Integer> v : list) {
            try {
                sum += v.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        Integer verifySum = 0;
        for (int i = 1; i <= num; i++) {
            verifySum += i * 1000;
        }

        System.out.println();
        System.out.println("多线程计算累计总和:" + sum);
        System.out.println("主线程校验累计总和:" + verifySum);

        if(!threadPool.isShutdown()){
            threadPool.shutdown();
        }



    }
}

3、任务线程类

package javabasic.thread;

import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {

    private String name;
    private Integer s;
    private Integer num;

    public MyCallable(String name, Integer s, Integer num) {
        this.name = name;
        this.s = s;
        this.num = num;
    }

    @Override
    public Integer call() throws Exception {
        System.out.println("线程" + name + " Ready to work");
        Thread.currentThread().sleep(s * num);
        Integer data = s * num;
        System.out.println("线程" + name + " task done,中间结果:" + data);
        return data;
    }

}

输出打印

线程2 Ready to work
线程3 Ready to work
线程1 Ready to work
线程4 Ready to work
线程5 Ready to work
线程1 task done,中间结果:1000
线程6 Ready to work
线程2 task done,中间结果:2000
线程7 Ready to work
线程3 task done,中间结果:3000
线程8 Ready to work
线程4 task done,中间结果:4000
线程9 Ready to work
线程5 task done,中间结果:5000
线程10 Ready to work
线程6 task done,中间结果:6000
线程7 task done,中间结果:7000
线程8 task done,中间结果:8000
线程9 task done,中间结果:9000
线程10 task done,中间结果:10000

多线程计算累计总和:55000
主线程校验累计总和:55000

标签:task,java,批量,work,线程,Integer,Ready,done,多线程
来源: https://blog.csdn.net/jiahao1186/article/details/122075183