This is the 24th day of my participation in the August Text Challenge.More challenges in August

preface

Accumulate a little bit every day, product short step to thousands of miles. Learn CyclicBarrier and ReentrantLock in JUC packages.

CyclicBarrier

A CyclicBarrier is a tool class that acts like a gate, allowing a group of threads to wait until all threads have reached the gate (also known as a common barrier point). All threads in the same group are guaranteed to execute at the same time. Unlike CountDownLatch, the barrier can be reused once it is released. The barrier closes immediately after the latch is opened, blocking the second group of threads. So that’s why they’re called Cyclic barriers

Code sample

public class CyclicBarrierSample {
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 1 ; i<=20 ; i++) {
            final int index = i;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            executorService.execute(new Runnable() {
                @Override
                public void run(a) { go(); }}); } executorService.shutdown(); }private static void go(a){
        System.out.println(Thread.currentThread().getName() + ": Ready" );
        try {
            cyclicBarrier.await();
            System.out.println(Thread.currentThread().getName() + ": Running");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch(BrokenBarrierException e) { e.printStackTrace(); }}}Copy the code
  • cyclicBarrier.await()Set a barrier point and run the following code when the total of five threads are ready
  • The printed results can be seen as a group of five, divided into four times completed.

Application scenarios

Multiple threads execute simultaneously at the same time

  • cpuThe performance evaluation
  • Seconds kill scenes
  • Ticket snatching robot

ReentrantLock

  • ReentrantLockReentrant lock, when any thread acquires the lock again without being blocked by the lock.
  • ReentrantLockThe goal is to replacesynchronizedThe keyword

The difference between ReentrantLock and synchronized

Characteristics of the Synchronized (recommended) reentrantLock
The underlying principle JVMimplementation JDKimplementation
The performance difference between Low – > high (JDK1.5 +) high
The release of the lock Auto release (compiler guaranteed) Manual release (finally)
The degree of coding simple complex
The granularity of the lock Undifferentiated reading and writing Read lock, write lock
Advanced features There is no Fair lock, unfair lock wake up,ConditionGroup wake up, interrupt wait lock

Code sample

public class ReentrantLockSample {
    public static int users = 100;// The number of concurrent access users simulated at the same time
    public static int downTotal = 50000; // The real total number of downloads by users
    public static int count = 0;/ / counter
    private static ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) {
        // scheduler, concurrent package support for concurrency provided after JDK1.5
        ExecutorService executorService = Executors.newCachedThreadPool();
        // Semaphore, the number of people used to simulate concurrency
        final Semaphore semaphore = new Semaphore(users);
        for (int i = 0; i < downTotal; i++) {
            executorService.execute(() -> {
                // Simulate N users' concurrent access and download through multiple threads
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch(Exception e) { e.printStackTrace(); }}); }try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();// Disable the scheduling service
        System.out.println("Total downloads:" + count);
    }
    // The thread is not safe
    public static void add(a) {
        lock.lock();/ / lock
        try {
            count++;
        } finally {
            lock.unlock(); // Unlock, be sure to place it in finally otherwise deadlock will occur}}}Copy the code

It is generally not recommended to use this method in real development. Firstly, it needs to release resources manually every time, and any negligence will cause serious consequences. Secondly, synchronized performance is not bad after JDK1.5.