Home > Java > javaTutorial > Summary of knowledge points on three synchronization tools of Java threads, collection notes

Summary of knowledge points on three synchronization tools of Java threads, collection notes

php是最好的语言
Release: 2018-07-28 16:11:20
Original
1897 people have browsed it

I recently encountered a question about the three synchronization tool classes of Java threads in an interview. I couldn’t remember it until I reviewed it. I didn’t study the synchronization tool class carefully when I was learning multi-threading, and now I have even forgotten it. Therefore, I reviewed it again and found it quite profound, so I compiled it and wrote an article for your reference. apache php mysql

Java provides us with three synchronization tool classes:

  • CountDownLatch (lock):

    ## A thread waits for other threads to finish executing before it executes (other threads wait for a thread to finish executing before it executes)


  • CyclicBarrier (barrier):

    A group of threads wait for each other to reach a certain state, and then the group of threads execute at the same time.


  • Semaphore:

    Controls a group of threads to execute simultaneously.


In fact, these tool classes are to be able to

better control the communication issues between threads~

1. CountDownLatch

1.1 Introduction to CountDownLatch

    ##A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
Simply put: CountDownLatch is a synchronization auxiliary class,
allows one or more threads to wait

until other threadsCompletetheir operations. There are actually two commonly used APIs: await()

and

countDown()

use Description: Summary of knowledge points on three synchronization tools of Java threads, collection notes

count initializes CountDownLatch, and then the thread that needs to wait calls the await method. The await method will block until count=0. After other threads complete their operations, they call
    countDown()
  • to decrement the counter count by 1.

    When the count is reduced to 0, all waiting threads will be released

    To put it bluntly, the waiting is controlled through the
  • count variable
  • , If the

    count value is 0 (the tasks of other threads have been completed), then execution can continue.

    1.2 CountDownLatch example
Example: 3y is now an intern, and other employees have not yet gotten off work. 3y is embarrassed to leave first, waiting for all other employees to leave. It’s 3 days before leaving.

import java.util.concurrent.CountDownLatch;

public class Test {

    public static void main(String[] args) {

        final CountDownLatch countDownLatch = new CountDownLatch(5);

        System.out.println("现在6点下班了.....");

        // 3y线程启动
        new Thread(new Runnable() {
            @Override
            public void run() {
           
                try {
                    // 这里调用的是await()不是wait()
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("...其他的5个员工走光了,3y终于可以走了");
            }
        }).start();

        // 其他员工线程启动
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("员工xxxx下班了");
                    countDownLatch.countDown();
                }
            }).start();
        }
    }
}
Copy after login

Output result:

Write another example: 3y is now responsible for the warehouse module function, but his ability is too poor and he writes very slowly, Summary of knowledge points on three synchronization tools of Java threads, collection notesOther employees need to wait until 3y has finished writing before they can continue writing.

import java.util.concurrent.CountDownLatch;

public class Test {

    public static void main(String[] args) {

        final CountDownLatch countDownLatch = new CountDownLatch(1);

        // 3y线程启动
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("3y终于写完了");
                countDownLatch.countDown();

            }
        }).start();

        // 其他员工线程启动
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("其他员工需要等待3y");
                    try {
                        countDownLatch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("3y终于写完了,其他员工可以开始了!");
                }
            }).start();
        }
    }
}
Copy after login
Output result:

2. CyclicBarrierSummary of knowledge points on three synchronization tools of Java threads, collection notes

2.1 Introduction to CyclicBarrier

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called
    cyclic
  • because it can be re-used after the waiting threads are released.

  • In simple terms: CyclicBarrier allows a group of threads to wait for each other until
Reach a certain public barrier point
. It is called cyclic because when all waiting threads are released, CyclicBarrier can

be reused (in contrast to CountDownLatch, which cannot be reused) Instructions for use:

CountDownLatch focuses on
    waiting for other threads to complete
  • , and CyclicBarrier focuses on: when the thread

    reaches a certain state , it pauses and waits for other threads, all threads arrive After, continue execution.

    2.2 CyclicBarrier Example
Example: 3y and his girlfriend made an appointment to go to Guangzhou Ye Shanghai to eat. Since 3y and 3y’s girlfriend live in different places, they naturally went The path is also different. So they agreed to meet

at

Tiyu West Road subway station, and agreed to send a message to Moments

when they met each other.

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

public class Test {

    public static void main(String[] args) {

        final CyclicBarrier CyclicBarrier = new CyclicBarrier(2);
        for (int i = 0; i < 2; i++) {

            new Thread(() -> {

                String name = Thread.currentThread().getName();
                if (name.equals("Thread-0")) {
                    name = "3y";
                } else {
                    name = "女朋友";
                }
                System.out.println(name + "到了体育西");
                try {

                    // 两个人都要到体育西才能发朋友圈
                    CyclicBarrier.await();
                    // 他俩到达了体育西,看见了对方发了一条朋友圈:
                    System.out.println("跟" + name + "去夜上海吃东西~");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
Copy after login
Test result:

After playing for a day, Summary of knowledge points on three synchronization tools of Java threads, collection notes each returned home

, 3y and his girlfriend agreed to

each Chat after taking a shower

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

public class Test {

    public static void main(String[] args) {

        final CyclicBarrier CyclicBarrier = new CyclicBarrier(2);
        for (int i = 0; i < 2; i++) {

            new Thread(() -> {

                String name = Thread.currentThread().getName();
                if (name.equals("Thread-0")) {
                    name = "3y";
                } else {
                    name = "女朋友";
                }
                System.out.println(name + "到了体育西");
                try {

                    // 两个人都要到体育西才能发朋友圈
                    CyclicBarrier.await();
                    // 他俩到达了体育西,看见了对方发了一条朋友圈:
                    System.out.println("跟" + name + "去夜上海吃东西~");

                    // 回家
                    CyclicBarrier.await();
                    System.out.println(name + "洗澡");

                    // 洗澡完之后一起聊天
                    CyclicBarrier.await();

                    System.out.println("一起聊天");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
Copy after login
Test result:

三、Semaphore

3.1Semaphore简介

Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource.

  • A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each {@link #acquire} blocks if necessary until a permit is available, and then takes it. Each {@link #release} adds a permit,potentially releasing a blocking acquirer.However, no actual permit objects are used; the {@code Semaphore} just

keeps a count of the number available and acts accordingly.

Semaphore(信号量)实际上就是可以控制同时访问的线程个数,它维护了一组"许可证"

  • 当调用acquire()方法时,会消费一个许可证。如果没有许可证了,会阻塞起来

  • 当调用release()方法时,会添加一个许可证。

  • 这些"许可证"的个数其实就是一个count变量罢了~

3.2Semaphore例子

3y女朋友开了一间卖酸奶的小店,小店一次只能容纳5个顾客挑选购买,超过5个就需要排队啦~~~

import java.util.concurrent.Semaphore;

public class Test {

    public static void main(String[] args) {

        // 假设有50个同时来到酸奶店门口
        int nums = 50;

        // 酸奶店只能容纳10个人同时挑选酸奶
        Semaphore semaphore = new Semaphore(10);

        for (int i = 0; i < nums; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    // 有"号"的才能进酸奶店挑选购买
                    semaphore.acquire();

                    System.out.println("顾客" + finalI + "在挑选商品,购买...");

                    // 假设挑选了xx长时间,购买了
                    Thread.sleep(1000);

                    // 归还一个许可,后边的就可以进来购买了
                    System.out.println("顾客" + finalI + "购买完毕了...");
                    semaphore.release();



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

        }

    }
}
Copy after login

输出结果:

Summary of knowledge points on three synchronization tools of Java threads, collection notes

反正每次只能5个客户同时进酸奶小店购买挑选。

总结:本文简单的介绍了一下Java多线程的三个同步工具类的用处以及如何用,要深入还得看源码或者查阅其他的资料。如果文章有错的地方欢迎指正,大家互相交流。

相关文章:

Java基础之线程同步

关于Java线程同步和同步方法的详解

相关视频:

Java多线程与并发库高级应用视频教程

The above is the detailed content of Summary of knowledge points on three synchronization tools of Java threads, collection notes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template