Multithreading to implement an accumulation (can be specific business) operation

Common practice

Add 100 directly here

 public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        Integer count = 100;
        Integer sum = 0;
        for (int a = 0; a < count; a++) {
            sum += a;
            Thread.sleep(100);

        }
        System.out.println(String.format("result:%d\n Time consuming:%d", sum, System.currentTimeMillis() - start));
    }

Execution result: result: 4950 time consuming: 10054

You can see it takes 10 seconds;

Optimization plan

Implement accumulation through asynchronous thread execution

 

public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        Integer count = 100;
        CountDownLatch countDownLatch = new CountDownLatch(count);
        AtomicInteger sum = new AtomicInteger(0);
        for (int a = 0; a < count; a++) {
            final Integer e = a;
            new Thread(
                    ()->{
                        sum .getAndAdd(e);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
                        countDownLatch.countDown();
                    }
            ).start();
        }
        countDownLatch.await();
        System.out.println(String.format("result:%d\n Time consuming:%d", sum.get(), System.currentTimeMillis() - start));
    }

Execution result: result: 4950 time consuming: 159

 

Summary:

Note for multithreading scheme:

  • 1. Thread safety?
    In this case, AtomicInteger is used, which is thread safety and ensures data correctness
  • 2. When can so many threads execute at the same time?
    Here, CountDownLatch is used to inform the program that the calculation has been completed after the last calculation, saving the waiting time

Let's talk about it here Thread.sleep(100); the purpose is to represent the time-consuming business logic. In the case of simple digital accumulation, 100 threads are not needed, and single thread is faster.

Also, the use of CountDownLatch should be noted.

 

Reprint of this article: thank the original author, https://blog.csdn.net/weixin_37910453/article/details/86523454

Keywords: Programming

Added by Mr.Shawn on Wed, 20 May 2020 17:08:55 +0300