Java多线程并发 汇总结果值

工作需要遍历多台服务器拿一个结果值进行汇总计算

样例代码 Demo

package com.atyang.flinkcdc;

import java.util.*;

public class RunnableTest {

    public static void main(String[] args) throws Exception {
        System.out.println("使用 Runnable 获得返回结果:");

        List workers = new ArrayList<>(10);
        List tasks = new ArrayList<>(10);

        // 新建 10 个线程,每个线程分别负责累加 1~10, 11~20, ..., 91~100
        for (int i = 0; i < 10; i++) {
            AccumRunnable task = new AccumRunnable(i * 10 + 1, (i + 1) * 10);
            Thread worker = new Thread(task, "慢速累加器线程" + i);

            tasks.add(task);
            workers.add(worker);

            worker.start();
        }

        List> total = new ArrayList<>(16);
        for (int i = 0, s = workers.size(); i < s; i++) {
            workers.get(i).join();  // 等待线程执行完毕
            total.add(tasks.get(i).getIntegerList());
        }

        System.out.println("\n累加的结果: " + total);
    }

    static final class AccumRunnable implements Runnable {

        private final int begin;
        private final int end;

        private List integerList;

        public AccumRunnable(int begin, int end) {
            this.begin = begin;
            this.end = end;
        }

        @Override
        public void run() {
            integerList = new ArrayList<>();
            try {
                for (int i = begin; i <= end; i++) {
                    integerList.add(i);
                    Thread.sleep(100);
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace(System.err);
            }
            System.out.printf("(%s) - 运行结束,结果为 %s\n",
                    Thread.currentThread().getName(), integerList);
        }

        public List getIntegerList() {
            return integerList;
        }
    }

}
1634047584(1).png

你可能感兴趣的:(Java多线程并发 汇总结果值)