Simple application of java multithreading, CountDownLatch and ExecutorService

CountDownLatch can ensure that the program executes the main thread after the sub-threads are all executed.

How to use: Set the initial value of the CountDownLatch object. After each thread is executed, call the countDown method, and the counter is decremented by 1. After all threads are executed, the counter is 0, and the main thread continues to be executed. code show as below:

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {
	public static void main(String[] args) throws InterruptedException {
		CountDownLatch startSignal = new CountDownLatch(1);
		CountDownLatch doneSignal = new CountDownLatch(4);
		
		new Thread(new Worker(startSignal, doneSignal)).start();
		new Thread(new Worker(startSignal, doneSignal)).start();
		new Thread(new Worker(startSignal, doneSignal)).start();
		new Thread(new Worker(startSignal, doneSignal)).start();

		System.out.println("Main program execution...");//Because startSignal is 1, the 4 threads above cannot be executed yet
		startSignal.countDown(); // startSignal=0, the thread can start executing
		doneSignal.await(); // Wait for the child thread to finish executing, then continue to execute the following code

		System.out.println("Start executing subsequent tasks...");
	}
}
class Worker implements Runnable {
	private final CountDownLatch startSignal;
	private final CountDownLatch doneSignal;

	Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
		this.startSignal = startSignal;
		this.doneSignal = doneSignal;
	}

	@Override
	public void run() {
		try {
			startSignal.await(); //Has the count of startSignal reached 0? to 0 to execute
			doWork();
			doneSignal.countDown(); //count minus 1
		} catch (InterruptedException ex) {
		}
	}

	void doWork() {
		System.out.println("Sub thread execution...");
	}
}

ExecutorService is used to help manage the thread pool. The thread task calls submit to submit and closes after execution.

ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0; i < threadNum; i++){
            executorService.submit(new Worker(startSignal, doneSignal));
        }
        try {
            doneSignal.await(); //The main thread can resume executing its own tasks through the await() method
        } catch (InterruptedException e){
            e.printStackTrace ();
        }
        doOtherThing()
        executorService.shutdown();




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324842859&siteId=291194637