


Summary of knowledge points on three synchronization tools of Java threads, collection notes
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):
- Semaphore: Controls a group of threads to execute simultaneously.
better control the communication issues between threads~
1. CountDownLatch1.1 Introduction to CountDownLatchallows one or more threads to wait##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,
until other threadsCompletetheir operations. There are actually two commonly used APIs: await()
andcountDown()
use Description:
- 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
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();
}
}
}
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, Other 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(); } } }Output result:
2. 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. It is called cyclic because when all waiting threads are released, CyclicBarrier cancyclic
Reach a certain public barrier point- 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
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
at
Tiyu West Road subway station, and agreed to send a message to Momentswhen 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(); } } }Test result:
After playing for a day, each returned home
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(); } } }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(); } } }
输出结果:
反正每次只能5个客户同时进酸奶小店购买挑选。
总结:本文简单的介绍了一下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!

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.