Java concurrent programming, introducing commonly used auxiliary classes
Related 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?1 2 3 4 5 6 7 8 9 |
|
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
1 2 3 4 5 6 7 8 9 10 11 12 |
|
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.
1 |
|
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
截图
3.Semophore
3.1.Semophore简介
前面讨论的问题都是多对一的问题,我们现在可以讨论多对多的问题了。
假设有7个兄弟开车上班,而现在只有4个车位。7部车并列开进4个车位,每个车停了多长时间未知,资源被占用完了。假设有一个车只停了2s,那么它走了,外面的车又可以进来了。走一个进一个,最后全部都可以进去。而semophore就是控制多线程的并发策略。
简单理解来说,Semaphore:信号量主要用于两个目的:一个是用于多个共享资源的互斥使用;另一个用于并发线程数量的控制。
Semaphore类有两个重要方法
1、semaphore.acquire();
请求一个信号量,这时候信号量个数-1,当减少到0的时候,下一次acquire不会再执行,只有当执行一个release()的时候,信号量不为0的时候才可以继续执行acquire
2、semaphore.release();
释放一个信号量,这时候信号量个数+1,
3.2.抢车位问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
运行结果截图:
3.3.原理总结
在信号量上我们定义两种操作:
acquire(获取)当一个线程调用acquire操作时,它要么通过成功获取信号量(信号量减1),要么一直等待下去,直到有线程释放信号量,或超时。
release(释放)实际上会将信号量的值加1,然后唤醒等待的线程。
信号量主要用于两个目的:一个是用于多个共享资源的互斥使用;另一个用于并发线程数量的控制
如果把资源数从3变成1了,此时就等价于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

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

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)

Hot Topics





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

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.

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 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.

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

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

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.
