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)A group of threads wait for each other to reach a certain state, and then the group of threads execute at the same time.
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:
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 callWhen the count is reduced to 0, all waiting threads will be released
count value is 0 (the tasks of other threads have been completed), then execution can continue.
1.2 CountDownLatch exampleimport 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(); } } }
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(); } } }
2. CyclicBarrier
2.1 Introduction to CyclicBarrierA 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
reaches a certain state , it pauses and waits for other threads, all threads arrive After, continue execution.
2.2 CyclicBarrier Examplewhen 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(); } } }
After playing for a day, each returned home
, 3y and his girlfriend agreed toeach 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(); } } }
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变量罢了~
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!