Usage of java CountDownLatch class

A counter is maintained in the CountDownLatch class. When the counter is 0, all threads are released. This class can be used to operate when all resources are initialized.

The await method in CountDownLatch waits for the counter to reach 0, indicating that all threads have finished executing. If the counter is not 0, the await() method will block until the counter becomes 0. The countDown() method is used to decrement the counter.

Here is an example of calculating execution time:

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {
	
	public static Long getMillions(){
		// Equivalent to establishing a starting line
		 final CountDownLatch startDownLatch = new CountDownLatch(1);
		 // Release after 10 threads are executed
		 final  CountDownLatch endCountDownLatch = new CountDownLatch(10);
		 for(int i=0;i<10;i++){
			 Thread thread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						//Wait for the tech in startDownLatch to drop to 0
						startDownLatch.await();
						System.out.println(Thread.currentThread().getName());
					} catch (InterruptedException e) {
						e.printStackTrace ();
					}finally {
						//The counter in endCountDownLatch is decremented by one
						endCountDownLatch.countDown();
					}
					
				}
			});
			 
			 thread.start();
		 }
		 Long startMillions = System.currentTimeMillis();
		 // all threads start executing
		 startDownLatch.countDown();
		
		 try {
			 //After all threads are executed, release when the counter of endCountDownLatch is equal to 0
			endCountDownLatch.await();
			System.out.println(System.currentTimeMillis()-startMillions);
		} catch (InterruptedException e) {
			e.printStackTrace ();
		}
		 return null;
	}
	
	public static void main(String[] args) {
		getMillions();
	}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326607493&siteId=291194637