Brush 19 interview questions: What tools Concurrency Kit?

image.png


java.util.concurrent package provides a large number of concurrent tool.


Hello everyone, I'm Li Fuchun, the topics are:

the Java tools provide concurrent What?

A: java.util.concurrent tool kit provided in four categories.

A synchronization tools, CountDownLatch, CyclicBarrier, Semaphore;
two, concurrency-safe containers, of ConcurrentHashMap, a ConcurrentSkipListMap,
a CopyOnWriteArrayList, CopyOnWriteArraySet;
three, concurrency-safe queue, mainly used in the thread pool, ArrayBlockingQueue, SynchronousQueue, PriorityBlockingQueue;
four concurrent thread pool executor frame ;


Synchronization Tool

semaphore


Semaphores, concurrent access to set the number of threads.

Pair generally used: try {s.acquire ();} finally {s.release ()}

package org.example.mianshi.synctool;

import java.util.concurrent.Semaphore;

/**
 * 创建日期:  2020/3/30 14:24
 * 描述:     信号量应用
 *
 * @author lifuchun
 */

public class SemaphoreApp {


    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(0);

        for (int i = 1; i <= 10; i++) {
            new MyThread(semaphore).start();
        }

        System.out.println("go ```");
        semaphore.release(5);


    }

    public static class MyThread extends Thread {

        private Semaphore semaphore;

        public MyThread(Semaphore semaphore) {
            this.semaphore = semaphore;
        }

        @Override
        public void run() {

            try {

                semaphore.acquire();

                System.out.println(System.currentTimeMillis() + " :" + Thread.currentThread().getName() + " -execute ```");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }


        }
    }


}复制代码

CountDownLatch


Set thread waits for completion of certain operations;

other thread finishes, call c.countDown ()

when the c value = 0, i.e., other threads to execute () method of logic behind await.

package org.example.mianshi.synctool;

import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;

/**
 * 创建日期:  2020/3/30 14:38
 * 描述:     countDownLatch的例子
 * @author lifuchun
 */

public class CountDownLatchApp {

    public static void main(String[] args) {

        CountDownLatch countDownLatch = new CountDownLatch(5);

        new Thread(() -> {

            try {
                countDownLatch.await();

                System.out.println("后置任务");


            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();


        IntStream.rangeClosed(1, 10)
                .forEach(i -> new MyThread(countDownLatch).start());


    }

    public static class MyThread extends Thread {

        private CountDownLatch countDownLatch;

        public MyThread(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {

            countDownLatch.countDown();

            System.out.println("前置任务");


        }
    }

}复制代码

CyclicBarrier


Allows multiple threads simultaneously reach a barrier. Set the number of concurrently executing threads.

Usually the await call () method, when the number reaches the preset number N, the unified execution logic behind the await method (), will automatically reset.

package org.example.mianshi.synctool;

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

/**
 * 创建日期:  2020/3/30 14:49
 * 描述:     cyclicBarrier的应用
 *
 * @author lifuchun
 */

public class CyclicBarrierApp {

    public static void main(String[] args) {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, CyclicBarrierApp::run);

        IntStream.rangeClosed(1, 30)
                .forEach(i -> new MyThread(cyclicBarrier).start());

    }

    private static void run() {
        System.out.println("reset , start again !");
    }

    public static class MyThread extends Thread {

        private CyclicBarrier cyclicBarrier;

        public MyThread(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {

            try {
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }

            System.out.println("do my work!");

        }
    }

}复制代码

image.png


Synchronization secure container


Class hierarchy as shown below:
image.png



scene selection:

1, if the focus is placed and concurrent acquisition speed, use of ConcurrentHashMap; 

2, if the focus sequence, and a large number of concurrent modification data frequently, using a ConcurrentSkipListMap


CopyOnWrite * replication defense:

the Add, SET, remote operation will copy the original array, replacing the original array after the changes are complete, the price is relatively large, suitable for reading and writing little scenes;



summary


Benpian answered java.util.concurrent tool kit classification introduces three sync tool, Semaphore, CountDownLatch, CyclicBarrier;

then the class hierarchy shown in FIG concurrency-safe containers, analyzed how different scenarios select the appropriate concurrent secure container.


image.png

The original is not easy, please indicate the source, let us complementarity and common progress, welcomed the communication.

Guess you like

Origin juejin.im/post/5e819ea5e51d45471654fc16