Java concurrent programming, introducing commonly used auxiliary classes
Feb 02, 2021 pm 05:38 PMRelated free learning recommendations: java basic tutorial
Commonly used auxiliary classes
- 1.CountDownLatch
- ##1.2. Example: Monitor door lock problem
- 1.2. Introduction to CountDownLatch class:
- 1.2.1 CountDownLatch concept
- 1.2.3 Usage of CountDownLatch
1.3.CountDownLatch case: - 1.4. Summary of principles
2.CyclicBarrier- 2.1.Introduction to CyclicBarrier
- 2.2.Case : Collect 7 dragon balls to summon the dragon
3.Semophore- 3.1.Introduction to Semophore
- 3.2. The problem of grabbing parking spaces
- 3.3. Summary of principles
1.CountDownLatch
1.2.Example: Monitor locks the door Problem
Problem description: Suppose there are 7 students studying in the evening. The key is in the hands of the monitor, and he is responsible for locking the door. The monitor must wait until everyone is gone before he can turn off the lights and lock the door. The order of these six students is disordered, and I don’t know when they left. Each of the six students took their own self-study classes, with no interaction in between. Suppose the 6 students are ordinary threads and the monitor is the main thread. How can we make the main thread wait for a bunch of threads to finish running before the main thread can finish running?public?class?CountDownLatchDemo?{ public?static?void?main(String[]?args)?{ //?TODO?Auto-generated?method?stub for(int?i=1;i{ System.out.println(Thread.currentThread().getName()+"\t離開教室"); },String.valueOf(i)).start(); } System.out.println(Thread.currentThread().getName()+"\t班長(zhǎng)關(guān)門走人"); }}Screenshot of running results
Finally, there are three people locked in the teacher. This may cause an accident, so it is definitely not possible.
1.2. Introduction to the CountDownLatch class:
1.2.1 CountDownLatch concept
CountDownLatch is a synchronization tool class used to coordinate synchronization between multiple threads, or to communicate between threads (rather than serving as a mutual exclusion).
CountDownLatch enables a thread to wait for other threads to complete their work before continuing to execute . Use a counter to implement. The initial value of the counter is the number of threads. When each thread completes its task, the counter value is decremented by one. When the counter value is 0, it means that all threads have completed some tasks, and then the threads waiting on CountDownLatch can resume executing the next tasks .
CountDownLatch description: count count, count down, start Latch1.2.3 Usage of CountDownLatch
A certain thread starts at the beginning Wait for n threads to complete execution before running. Initialize the CountDownLatch counter to new CountDownLatch(n). Whenever a task thread completes execution, the counter is decremented by 1 countdownLatch.countDown(). When the counter value becomes 0, the thread await() on CountDownLatch will be awakened. A typical application scenario is that when starting a service, the main thread needs to wait for multiple components to be loaded before continuing execution. CountDownLatch underlying constructor source code
public?CountDownLatch(int?count)?{ ????????if?(count?<p>1.3.CountDownLatch case: <strong></strong></p><pre class="brush:php;toolbar:false">public?static?void?main(String[]?args)?throws?InterruptedException?{ //6個(gè)同學(xué)正在上自習(xí),每個(gè)人就有一個(gè)1計(jì)數(shù)器,走1個(gè)數(shù)字減1,main線程啟動(dòng),必須要等計(jì)時(shí)器從6變成0,才能開始。 CountDownLatch?countDownLatch=new?CountDownLatch(6); for(int?i=1;i{ System.out.println(Thread.currentThread().getName()+"\t離開教室"); countDownLatch.countDown(); //計(jì)算減少一個(gè) },String.valueOf(i)).start(); } countDownLatch.await(); //班長(zhǎng)前面需要被阻塞 System.out.println(Thread.currentThread().getName()+"\t班長(zhǎng)關(guān)門走人"); }Run result screenshot
Here We don’t know when everyone will leave, but we can guarantee that the squad leader will be the last to leave every time.
1.4. Principle summary
CountDownLatch mainly has two methods. When one or more threads call the await method, these threads will be blocked. Calling the countDown method by other threads will decrement the counter by 1 (the thread calling the countDown method will not be blocked)
When the counter value becomes 0, the thread blocked by the await method will be awakened and execution will continue.
2.CyclicBarrier
2.1. Introduction to CyclicBarrier
cyclic cycle, barrier barrier. From the literal meaning, the Chinese meaning of this class is "circulating fence". It roughly means a recyclable barrier.
Its function is to make all threads wait for completion before continuing to the next step. The above example of the monitor closing the door is to do a countdown, here it is the other way around, to do addition, and start when the number is reached.
For example, when everyone is here, start the meeting again. , for example, just like in life, we will invite colleagues to go to a meeting. Some colleagues may arrive early and some colleagues may arrive late. However, the meeting stipulates that we must wait until everyone has arrived before we can officially Have a meeting. The colleagues here are the threads, and the meeting is the CyclicBarrier.
public?CyclicBarrier(int?parties)public?CyclicBarrier(int?parties,?Runnable?barrierAction)Analysis:
parties is the number of participating threads The second construction method has a Runnable parameter, which means the last one To reach the task to be done by the thread
2.2. Case: Collect 7 Dragon Balls to Summon the Dragon
public?static?void?main(String[]?args)?{ //?TODO?Auto-generated?method?stub CyclicBarrier?cyclicBarrier=new?CyclicBarrier(7,()->{System.out.println("召喚神龍");}); for(int?i=1;i{ System.out.println(Thread.currentThread().getName()+"\t收集到第"+tempInt+"顆龍珠"); try?{ //某個(gè)線程收集到了龍珠只能先等著,等龍珠收齊了才能召喚神龍 cyclicBarrier.await(); }?catch?(Exception?e)?{ //?TODO?Auto-generated?catch?block e.printStackTrace(); } },String.valueOf(i)).start();; } }
截圖
3.Semophore
3.1.Semophore簡(jiǎn)介
前面討論的問題都是多對(duì)一的問題,我們現(xiàn)在可以討論多對(duì)多的問題了。
假設(shè)有7個(gè)兄弟開車上班,而現(xiàn)在只有4個(gè)車位。7部車并列開進(jìn)4個(gè)車位,每個(gè)車停了多長(zhǎng)時(shí)間未知,資源被占用完了。假設(shè)有一個(gè)車只停了2s,那么它走了,外面的車又可以進(jìn)來了。走一個(gè)進(jìn)一個(gè),最后全部都可以進(jìn)去。而semophore就是控制多線程的并發(fā)策略。
簡(jiǎn)單理解來說,Semaphore:信號(hào)量主要用于兩個(gè)目的:一個(gè)是用于多個(gè)共享資源的互斥使用;另一個(gè)用于并發(fā)線程數(shù)量的控制。
Semaphore類有兩個(gè)重要方法
1、semaphore.acquire();
請(qǐng)求一個(gè)信號(hào)量,這時(shí)候信號(hào)量個(gè)數(shù)-1,當(dāng)減少到0的時(shí)候,下一次acquire不會(huì)再執(zhí)行,只有當(dāng)執(zhí)行一個(gè)release()的時(shí)候,信號(hào)量不為0的時(shí)候才可以繼續(xù)執(zhí)行acquire
2、semaphore.release();
釋放一個(gè)信號(hào)量,這時(shí)候信號(hào)量個(gè)數(shù)+1,
3.2.搶車位問題
public?static?void?main(String[]?args)?{ //模擬6部車搶3個(gè)空車位 Semaphore?semaphore=new?Semaphore(3);//模擬資源類,有3個(gè)空車位 for(int?i=1;i{ try?{ //誰(shuí)先搶到了,誰(shuí)就占一個(gè)車位,并且要把semaphore中的資源數(shù)減1 semaphore.acquire(); System.out.println(Thread.currentThread().getName()+"\t搶占到了車位"); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName()+"\t離開了車位"); }?catch?(Exception?e)?{ //?TODO?Auto-generated?catch?block e.printStackTrace(); }finally{ //釋放車位 semaphore.release(); } },String.valueOf(i)).start(); } }
運(yùn)行結(jié)果截圖:
3.3.原理總結(jié)
在信號(hào)量上我們定義兩種操作:
acquire(獲取)當(dāng)一個(gè)線程調(diào)用acquire操作時(shí),它要么通過成功獲取信號(hào)量(信號(hào)量減1),要么一直等待下去,直到有線程釋放信號(hào)量,或超時(shí)。
release(釋放)實(shí)際上會(huì)將信號(hào)量的值加1,然后喚醒等待的線程。
信號(hào)量主要用于兩個(gè)目的:一個(gè)是用于多個(gè)共享資源的互斥使用;另一個(gè)用于并發(fā)線程數(shù)量的控制
如果把資源數(shù)從3變成1了,此時(shí)就等價(jià)于synchronized。
The above is the detailed content of Java concurrent programming, introducing commonly used auxiliary classes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

How to handle concurrent access in Java backend function development? In modern Internet applications, high concurrent access is a common challenge. When multiple users access backend services at the same time, if concurrency is not handled correctly, it may cause problems such as data consistency, performance, and security. This article will introduce some best practices for handling concurrent access in Java backend development. 1. Use thread synchronization Java provides a variety of mechanisms to handle concurrent access, the most commonly used of which is thread synchronization. By adding synch before key code blocks or methods

Answer: The reflection mechanism allows Java programs to inspect and modify classes and objects at runtime through the reflection API, which can be used to implement flexible concurrency mechanisms in Java concurrency. Application: Dynamically create threads. Dynamically change thread priority. Inject dependencies.

How to create parallel tasks using Fork/Join framework in Java? Define task logic, calculate results or perform actions. Create a ForkJoinPool to manage parallel threads. Use the fork() method to submit tasks. Use the join() method to get the task results.

How to solve: Java Concurrency Error: Deadlock Detection Deadlock is a common problem in multi-threaded programming. A deadlock occurs when two or more threads wait for each other to release a locked resource. Deadlock will cause threads to be blocked, resources cannot be released, and programs cannot continue to execute, resulting in system failure. To solve this problem, Java provides a deadlock detection mechanism. Deadlock detection determines whether there is a deadlock by checking the dependencies between threads and the resource application queuing situation. Once a deadlock is found, the system can take corresponding measures.

Blocking Queue: A Powerful Tool for Concurrency and Multithreading Blocking Queue is a thread-safe queue that plays the following key roles in concurrent and multi-threaded programming: Thread Synchronization: Prevents race conditions and data inconsistencies by blocking operations. Data buffer: As a data buffer, it alleviates the problem of mismatch in producer and consumer thread speeds. Load balancing: Control the number of elements in the queue and balance the load of producers and consumers.

Ways to Solve Java Concurrency Race Condition Errors and Exceptions Race conditions refer to when multiple threads access and modify shared resources at the same time, and the correctness of the final result is affected by the order of execution. In Java, when multiple threads access shared resources concurrently, race condition errors will occur if the synchronization mechanism is not used correctly. When a race condition error occurs, the program may produce unexpected results or even crash. This article will discuss how to resolve Java concurrency race condition error exceptions. 1. The most common way to solve race conditions using synchronization mechanisms

How to solve: Java Concurrency Error: Thread Deadlock Introduction: Thread deadlock is a very common problem in concurrent programming. When multiple threads are competing for resources, deadlock may occur if the threads wait for each other to release resources. This article will introduce the concept of thread deadlock, its causes, and how to solve this problem. The concept of thread deadlock occurs when multiple threads wait for each other to release resources, causing all threads to be unable to continue executing, forming a thread deadlock. Thread deadlock usually occurs because the following four conditions are true at the same time

Both CountDownLatch and CyclicBarrier are used in multi-threaded environments, and they are both part of multi-threaded environments. According to JavaDoc - CountDownLatch - A synchronization aid that allows one or more threads to wait until a set of operations performed in other threads is completed. CyclicBarrier - A synchronization aid that allows a group of threads to wait for each other to reach a common barrier point. gentlemen. KeyCyclicBarrierCountDownLatch1 basically allows synchronization of a set of threads all waiting for each other to reach a common barrier point. A synchronization aid that allows one or more threads to wait for a set of operations performed in other threads.
