Multi-threaded programming learning nine (concurrent tools).

CountDownLatch

  1. CountDownLatch allows one or more threads waiting for other threads to finish.
  2. CountDownLatch can join the substitution effect, and provides a richer usage.
  3. The method countDown CountDownLatch, N will be reduced. 1; CountDownLatch await methods of blocking the current thread until N becomes zero.
  4. CountDownLatch impossible to re-initialize or modify the value of the internal counter CountDownLatch object.
  5. Internal CountDownLatch implemented by AQS shared lock.
public class CountDownLatchTest {

    private static final CountDownLatch DOWN_LATCH = new CountDownLatch(2);

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            System.out.println(1);
            DOWN_LATCH.countDown();
            System.out.println(2);
            DOWN_LATCH.countDown();

        }).start();
        DOWN_LATCH.await();
        System.out.println("3");
    }
}

CyclicBarrier

  1. CyclicBarrier set up a barrier (also called synchronization point), intercepted a group of threads blocked until the last thread reaches the barrier, the barrier will open the door, all barriers blocked thread will continue to run.
  2. CyclicBarrier default constructor is CyclicBarrier (int parties), its parameter indicates the number of threads barrier to intercept each thread calls await method tells CyclicBarrier I have reached the barrier, then the current thread is blocked.
  3. CyclicBarrier also offers a more advanced constructor CyclicBarrier (int parties, Runnable barrierAction), used in the thread reaches the barrier, take precedence barrierAction, easy to handle more complex business scenarios.
  4. getNumberWaiting ways to get the number of threads CyclicBarrier blocked; isBroken () method is used to find out if the blocked thread is interrupted.
  5. CyclicBarrier counter can reset () method to reset (only one counter CountDownLatch). So CyclicBarrier can handle more complex business scenarios. For example, if the calculated error occurs, you can reset the counter and let the thread again from the beginning.
  6. CyclicBarrier can be used for multi-threaded computing data, the combined results of the last scene.
  7. CyclicBarrier reentrant lock using internal ReentrantLock achieved.
public class BankWaterService implements Runnable {
 
    // 创建4个屏障,处理完之后执行当前类的run方法
    private CyclicBarrier barrier = new CyclicBarrier(4, this);
    // 假设有4个计算任务,所以只启动4个线程
    private Executor executor = Executors.newFixedThreadPool(4);
    // 保存每个任务的计算结果
    private ConcurrentHashMap<String, Integer> sheetBankWaterCount = new ConcurrentHashMap<>();

    private AtomicInteger atomicInteger = new AtomicInteger(1);

    private void count() {
        for (int i = 0; i < 4; i++) {
            Thread thread = new Thread(() -> {
                // 当前任务的计算结果,计算过程忽略
                sheetBankWaterCount.put(Thread.currentThread().getName(), 1);
                // 计算完成,插入一个屏障
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }

            }, "线程" + atomicInteger.getAndIncrement());
            executor.execute(thread);
        }
    }

    @Override
    public void run() {
        int result = 0;
        // 汇总每个任务计算出的结果
        for (Map.Entry<String, Integer> sheet : sheetBankWaterCount.entrySet()) {
            result += sheet.getValue();
        }
        //将结果输出
        sheetBankWaterCount.put("result", result);
        System.out.println(result);
    }

    public static void main(String[] args) {
        BankWaterService bankWaterCount = new BankWaterService();
        bankWaterCount.count();
    }
}

Semaphore

  1. Semaphore (Semaphore) is used to control the number of threads simultaneously access a particular resource, which through the coordination of the various threads, in order to ensure rational use of public resources.
  2. Semaphore can be used to do traffic control, in particular, with limited public resources application scenarios, such as database connection.
  3. Semaphore Constructor Semaphore (int permits) accepts an integer number representing the number of licenses available.
  4. First of all threads of Semaphore acquire () method to get a license, call the release () method to return the license after use. You can also use tryAcquire () method attempts to obtain a license.
  5. intavailablePermits (): Returns the number of licenses in this semaphore currently available.
  6. intgetQueueLength (): Returns the number of threads that are waiting to obtain a license.
  7. booleanhasQueuedThreads (): whether any threads are waiting to acquire a license.
  8. Semaphore internal use AQS achieve a shared lock.
public class SemaphoreTest {

    private static final int THREAD_COUNT = 30;
    private static ExecutorService EXECUTOR = Executors.newFixedThreadPool(THREAD_COUNT);
    private static Semaphore SEMAPHORE = new Semaphore(10);
    private static AtomicInteger ATOMICINTEGER = new AtomicInteger(1);

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            EXECUTOR.execute(() -> {
                try {
                    SEMAPHORE.acquire();
                    System.out.println("save data" + ATOMICINTEGER.getAndIncrement());
                    SEMAPHORE.release();
                } catch (InterruptedException e) {
                }

            });
        }
        EXECUTOR.shutdown();
    }
}

Exchanger

  1. Exchanger (exchanger) is a utility class for collaboration between threads - for the exchange of data between threads. It provides a synchronization point, in this synchronization point, two threads can exchange data with each other. These two threads to exchange data exchange method, if the first thread to execute exchange () method, which has been waiting for a second thread also performs exchange method.
  2. Exchanger objects can simply be understood as a container comprising two cells, the two cells may be filled in by the information exchanger method. When two cells are filled in, the object information is automatically exchanged two lattice, then returned to the thread, so that two information exchange threads.
  3. Exchanger can be used in genetic algorithms. (Genetic algorithms: to elect two people as a mate, this time the two will exchange data and rules derived using cross mating results)
  4. Exchanger can be used for proofreading, such as a data requires two people proofread, proofread and correct after all, in order to follow-up treatment. In this case, you can use Exchanger compare the two collation results.
  5. Exchanger lock-free internal CAS implemented so, Exchange uses two attributes of the objects inside the Node - item, match, distribution value stored two threads.
public class ExchangerTest {

    private static final Exchanger<String> exchange = new Exchanger<>();
    private static ExecutorService threadPool = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        threadPool.execute(() -> {
            try {
                String result = exchange.exchange("数据A");
                System.out.println("A的exchange结果:" + result);
            } catch (InterruptedException e) {
            }

        });
        threadPool.execute(() -> {
            try {
                String result = exchange.exchange("数据B");
                System.out.println("B的exchange结果:" + result);
            } catch (InterruptedException e) {
            }
        });
        threadPool.shutdown();
    }
}

Guess you like

Origin www.cnblogs.com/jmcui/p/11511413.html