Use of concurrent tools

One.CountDownLatch

(1 Overview

CountDownLatch is used to wait for multiple threads or thread steps to complete before proceeding to the next step.
构造函数Pass in the parameter count, and based on the AQS framework, set count as the internal state value of AQS.
Link: The principle and application of AQS The
Insert picture description here
execution countDown()方法of count is reduced by one, and the thread will be released only when count<0.
await()方法Used to block the thread, if you need to set the maximum blocking time of the thread, you can also use the await(long timeout,TimeUnit unit)method with parameters .
Insert picture description here

(2) Example code

package juctools;

import java.util.concurrent.CountDownLatch;

/**
 * @author 用于等待多线程完成
 */
public class CountDownLatchTest {
    
    
    private static CountDownLatch countDownLatch = new CountDownLatch(10);

    public static void main(String[] args) {
    
    
        int name = 1;
        for (int i = 0; i < 10; i++) {
    
    
            Person person = new Person(countDownLatch,name);
            new Thread(person).start();
            name++;
        }
        try {
    
    
            countDownLatch.await();
            System.out.println("所有任务均已完成!");
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }

    private static class Person implements Runnable {
    
    
        private CountDownLatch countDownLatch;
        private int name;

        public Person(CountDownLatch countDownLatch, int name) {
    
    
            this.countDownLatch = countDownLatch;
            this.name = name;
        }

        @Override
        public void run() {
    
    
            Thread.currentThread().setName("第"+name+"个人");
            System.out.println(Thread.currentThread().getName()+"完成任务!");
            countDownLatch.countDown();
        }
    }
}

Run screenshot:
Insert picture description here

二.CyclicBarrier

(1 Overview

CyclicBarrier means a reusable barrier . Its function is to temporarily block the thread at the barrier position. Only when the last thread reaches the barrier will it let the thread continue to execute .
The default construction method is CyclicBarrier(int parties), parties represents the number of threads that need to be intercepted. At the same time, there is another construction method: The CyclicBarrier(int parties, Runnable barrierAction)incoming Runnable object will be executed by the last thread after all threads reach the barrier.
When the await method is executed, it indicates that the thread has reached the barrier .

(2) The difference between CyclicBarrier and CountDownLatch

1. Different counting methods for judging thread interception

CyclicBarrier implements the addition count by executing the await method, and
CountDownLatch is the subtraction count.

2. Is it reusable

CyclicBarrier can reset the counter through the reset() method, but
CountDownLatch cannot be reset.

3. Different extended functionality

In addition to basic methods such as await and construction methods, CyclicBarrier also provides useful methods such as the getNumberWaiting method (to obtain the current number of blocked threads).

(3) Example code

package juctools;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author CyclicBarrier
 */
public class CyclicBarrierTest {
    
    
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(10,new Last());

    public static void main(String[] args) {
    
    
        for (int i = 1; i <= 10; i++) {
    
    
            new Thread(new Person(cyclicBarrier,i)).start();
        }
        try {
    
    
            Thread.currentThread().join();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 业务对象Person
     */
    private static class Person implements Runnable {
    
    
        private CyclicBarrier cyclicBarrier;
        private int name;

        public Person(CyclicBarrier cyclicBarrier, int name) {
    
    
            this.cyclicBarrier = cyclicBarrier;
            this.name = name;
        }

        @Override
        public void run() {
    
    
            System.out.println("第"+name+"个人已经到达!");
            try {
    
    
                cyclicBarrier.await();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    /**
     * 所有线程到达之后执行的对象
     */
    private static class Last implements Runnable {
    
    
        @Override
        public void run() {
    
    
            System.out.println("所以人均已到达!出发!");
        }
    }
}

Effect screenshot:
Insert picture description here

三.Semaphore

(1 Overview

The function of the Semaphore class is to control the maximum number of threads concurrently executing a certain business.
The construction method is Semaphore(int permits), permits indicates the maximum number of threads allowed for concurrent execution, call the acquire()method to obtain the thread execution license, and call release()方法to return the license after use .

(2) Example code

Take thread pool as an example:

package juctools;

import java.util.concurrent.*;

/**
 * @author Semaphore
 */
public class SemaphoreTest {
    
    
    /**
     *共有10个线程
     */
    private static final int count = 10;
    /**
     *最多发放2个许可证
     */
    private static Semaphore s = new Semaphore(2);
    /**
     *手动创建线程池
     */
    static ThreadPoolExecutor tpe = new ThreadPoolExecutor(6,12,2,
            TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(3));

    private static class MyRunnable implements Runnable {
    
    
        private int index;

        public MyRunnable(int index) {
    
    
            this.index = index;
        }

        @Override
        public void run() {
    
    
            try {
    
    
                s.acquire();
                System.out.println("线程"+index+"获得许可,开始进入!");
                s.release();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
    
    
        for (int i = 1; i <= count; i++) {
    
    
            tpe.execute(new MyRunnable(i));
        }
        tpe.shutdown();
    }
}

Guess you like

Origin blog.csdn.net/m0_46550452/article/details/107591269