When multithreading completes a business, it needs to wait until all threads have finished the implementation of the logic after execution.

Keywords: Java

Recently in a project, multiple threads need to be opened to analyze data in batches, but follow-up operations must be performed after all data analysis is completed.

A simple implementation is recorded below:

Define a counter globally, initialize the number of times that need to be executed, subtract one operation each time a thread is executed, until all threads are executed, the counter will become zero, then the logic after the thread is executed when the counter is zero.

Using CountDownLatch objects in java can help us subtract one at the end of each thread, as follows:

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadTest {

    public static void main(String[] args) throws InterruptedException {
        // Create a fixed-size thread pool
        int TEST_THREAD_COUNT = 5;
        ExecutorService service = Executors.newFixedThreadPool(TEST_THREAD_COUNT);
        // Simulate 10 Timing Tasks
        for (int i = 0; i < 10; i++) {
            // Number of threads to start
            final CountDownLatch latch = new CountDownLatch(10);
            for (int j = 0; j < 10; j++) {
                // Analysis of each data
                int finalJ = j;
                service.execute(()->{
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        latch.countDown();
                        e.printStackTrace();
                    }
                    System.out.println("Analysis xx Classmate"+ finalJ);
                    latch.countDown();
                });
            }

            try{
                // Waiting for all threads to end
                latch.await();
            }catch (Exception e){
                e.printStackTrace();
            }

            System.out.println("Timing task"+i+"complete");
            Thread.sleep(10000);
        }
        System.out.println("All scheduled tasks are over!");
    }
}

 

 

 

 

 

 


 

 

 

Posted by saleemshehzad on Fri, 04 Oct 2019 13:38:18 -0700