List of high-quality authors
J**A Concurrency Basics: Phaser Comprehensive Analysis! - Programmer Goode Phaser is a flexible synchronization tool in J**a, its advantage is that it supports multi-stage task splitting and synchronization, and can dynamically register and log out participants, it provides a rich waiting and pushing mechanism, so that developers can control the coordination behavior of threads in a more fine-grained manner, to achieve complex parallel task processing, compared with other synchronization tools, Phaser is more flexible and easy to expand, suitable for a variety of concurrency scenarios.
In j**a,phaser
is a flexible synchronization utility class that allows multiple threads to coordinate on one or more barrier pointsphaser
Think of a multithreaded meetup organizer who is responsible for making sure that all the threads involved have reached a certain stage before moving on to the next step together.
Let's take a real-life scenario: Suppose you are developing a multiplayer game, for example, a team puzzle game, in which several players (threads) need to cooperate to complete a series of tasks to complete the level, each task is divided into several stages, and each stage requires all players to complete certain actions together before they can move on to the next stage.
In this scene,phaser
can play its role, and each stage can be seen as a barrier point, and each player thread will go to it after completing its own tasks in the current stagephaser
Report and then wait for the other players to complete once all players have completed the task for the current stagephaser
It will ring like a bell to notify all players that they are ready to move on to the next stage.
For example, in a puzzle game, four players need to find four different clues and combine them to open the door to the next levelphaser
I've done the job myself,phaser
Waits for all four players to find a clue before notifying them that they can combine the clues to open the door to the next level.
Phaser is mainly used to solve the synchronization problem of multiple threads to complete tasks together in stages, it can ensure that a group of threads are synchronized before reaching a certain barrier point (phase), that is, all threads have completed the tasks of a certain stage before they can enter the next stage together, this synchronization mechanism is especially suitable for situations that require multiple threads to cooperate to complete complex tasks, such as multiplayer games, distributed systems, parallel computing and other scenarios.
When a thread completes a task and reaches the barrier point, it will call the corresponding method of the phaser to notify the other threads, and then wait for the other threads to enter the next stage together, in this process, the phaser will manage the synchronization and cooperation of the threads, ensuring that all threads can complete their tasks in a predetermined order.
In addition, Phaser also provides flexible registration and unregistration of threads, can dynamically add or remove threads participating in synchronization, and also supports interrupt and timeout mechanisms, which can be interrupted or set timeouts while waiting for other threads, enhancing the flexibility of multi-threaded synchronization.
Here's a simple Ja example that demonstrates how to use itphaser
to synchronize multiple threads to ensure they complete their tasks in phases, as follows
import j**a.util.concurrent.phaser;
public class phaserexample catch (interruptedexception e)
Reach the barrier point again and wait for the other threads
phaser.arriveandawaitadvance();
system.out.println("Threads" + threadnum + ": The second stage of the quest is completed. ");
Simulate the tasks of the third stage
try catch (interruptedexception e)
The last time the barrier point is reached, and all threads are completed, the phaser will automatically enter the termination state
phaser.arriveandawaitadvance();
system.out.println("Threads" + threadnum + ": The third phase task is completed, and the phaser task is completed. ");
.start();
Wait for all threads to complete the task
Note: In practice, you may not want the main thread to block here, but to do something else
But for demonstration purposes, let the main thread wait for all worker threads to finish
phaser.awaitadvance(phaser.getphase())
system.out.println("The first stage task of all threads is completed. ");
phaser.awaitadvance(phaser.getphase() 1);
system.out.println("The second phase of the task for all threads is completed. ");
phaser.awaitadvance(phaser.getphase() 1);
system.out.println("The third stage task of all threads is completed, and the entire task is completed. ");
In the above, one was createdphaser
The instance initially registers three threads and the main thread, each of which executes three phases of tasks, and each stage of tasks passes between themphaser.arriveandawaitadvance()
methods are synchronized, and each thread, after completing the task of the current stage, blocks on this method until all other threads have also completed their tasks in the current stage, after all threads have completed the tasks of the last stagephaser
It will automatically enter a terminated state, and no more threads will be blocked.
The above ** output is as follows:
The main thread is also ready, waiting for the other threads.
Thread x is ready, waiting for other threads.
Thread y is ready, waiting for other threads.
Thread Z is ready, waiting for other threads.
Here all threads and the main thread wait until all participants have called arriveandawaitadvance).
The first stage of the main thread task is completed (in fact, the main thread may simply monitor or coordinate other threads).
The first phase of the thread x task is completed.
The first phase of the thread y task is completed.
The first phase of the thread z task is completed.
All threads and the main thread continue to execute until they call arriveandawaitadvance again).
The main thread completes a second-stage task (in fact, it may be waiting for other threads to complete some task).
The second phase of the thread x task is completed.
The second phase of the thread y task is completed.
The second phase of thread z task is complete.
All threads and the main thread continue to execute the third phase task).
The third phase of the main thread task is completed (which could actually be some cleanup or a rollup of the results).
The third phase of thread x completes and the phaser task ends.
The third phase of thread y is completed, and the phaser task is completed.
The third phase of thread Z is completed, and the phaser task is completed.
phaser
It allows a group of threads to wait for each other until all threads reach a certain barrier pointphaser
Ideal for multi-stage task splitting and syncing, here's what to look likephaser
A brief description of some of the important methods:
phaser(int parties)
: constructor, create a new onephaser
instance, and set the number of registered parties, which represents the number of threads that must reach the barrier before moving on to the next stage. phaser()
: constructor, create a new onephaser
instance, but does not set the number of threads registered, which is typically used for hierarchiesphaser
, among themphaser
will inherit the fatherphaser
The number of registered threads. register()
: Increase the number of threads required to reach the barrier, and if the thread calling this method is not already registered, it will also register itself as the thread that has not arrived. arrive()
: Indicates that the current thread has reached the barrier, and reduces the number of threads that have not arrived, if this is the last thread to arrive, and the barrier for the next stage has been set, then this method will returntrue
, otherwise returnfalse
arriveandawaitadvance()
: The current thread reaches the barrier and waits for the other threads to arrive as well, when all threads have arrived, the barrier automatically advances to the next stage, and then the method returns if it is currentphaser
is terminated, and the method will be thrownillegalstateexception
awaitadvance(int phase)
: Wait until the barrier advances to a given stage, and if the current stage is greater than or equal to the given stage, then this method will return immediately. isterminated()
: Checkphaser
Whether it has been terminated, when the number of registered threads is reduced to zero and no new threads are registeredphaser
will be terminated. getphase()
: Gets the stage number of the current barrier, each barrier has a unique stage number, and the initial stage number is 0. getregisteredparties()
: Obtain the number of currently registered threads. getarrivedparties()
: Gets the number of threads that have reached the current barrier. getunarrivedparties()
: Gets the number of threads that haven't reached the current barrier yet, which is actuallygetregisteredparties()
withgetarrivedparties()
difference between the values. forcetermination()
: Forced terminationphaser
, even if there are threads that haven't arrived, which causes all the waiting inarriveandawaitadvance()
orawaitadvance(int)
method on the thread throwillegalstateexception
onadvance(int phase, int registeredparties)
: This is a protected method that can be overridden in a subclass to perform custom actions as each barrier stage advances. bulkregister(int parties)
: Registers multiple threads at once, which is often used for a statically known number of threads, or when multiple tasks are represented by the same thread.
J**A Concurrency Basics: Phaser Comprehensive Analysis! - The purpose of the Programmer Goode phaser class is to allow synchronization of execution between multiple threads in concurrent programming, and it has the following advantages:
Better scalability: The phaser class has better scalability than other synchronization utility classes such as cyclicbarrier and countdownlatch because it supports more participants (i.e., threads) to synchronize at the same time. Automatic logout and cleanup: When all participants have completed the execution, Phaser will automatically log out and release related resources, which helps to avoid memory leaks and resource waste. Flexible Execution Modes: The Phaser class provides a variety of execution modes, such as parallel, serial, and hybrid modes, which makes it more flexible when dealing with concurrent tasks. It also has many disadvantages, such as: 1. Compared with other synchronization tool classes, the implementation of the phaser class is relatively complex, so additional performance overhead may be introduced in some scenarios, and the phaser class has a certain threshold for use, and the use of concurrent programming and j**a concurrent API is deeply understood, which may increase the learning cost.
Follow me and learn Internet programming techniques every day - programmer Goode end!