美文网首页
Java多线程并发 汇总结果值

Java多线程并发 汇总结果值

作者: 百年叔叔 | 来源:发表于2021-10-12 22:06 被阅读0次

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

    样例代码 Demo

    package com.atyang.flinkcdc;
    
    import java.util.*;
    
    public class RunnableTest {
    
        public static void main(String[] args) throws Exception {
            System.out.println("使用 Runnable 获得返回结果:");
    
            List<Thread> workers = new ArrayList<>(10);
            List<AccumRunnable> 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<List<Integer>> 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<Integer> 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<Integer> getIntegerList() {
                return integerList;
            }
        }
    
    }
    
    1634047584(1).png

    相关文章

      网友评论

          本文标题:Java多线程并发 汇总结果值

          本文链接:https://www.haomeiwen.com/subject/fpbjoltx.html