Detailed explanation of Java asynchronous processing mechanism examples

Usually, synchronization means that a processing process of a task will serialize multiple threads, while asynchrony means that a processing process can allow multiple threads to process at the same time. Let's take a look at the details of asynchronous processing.

Asynchrony usually represents better performance because it largely depends on buffering. It is a typical practice of using space for time. For example, in a computer, cache serves as a buffer zone between CPU and disk IO to coordinate the high-speed computing power of CPU and the low-speed reading and writing power of disk.

volatile

Application scenario: check the closing or interruption status of an application execution. Because this keyword rejects the optimization when the virtual machine assigns multiple values to a variable, it ensures that the virtual machine will check the state change of the variable modified by this keyword.

CountDownLatch

Application scenario: control that the current thread is waiting until a group of thread operations are completed. For example, execute the await () method in the main thread to block the main thread, and execute the countdown () method after the worker thread executes the logic.

This article example scenario:

1. Send a message from the console to the message server (simulated by a queue).

2. Write the message queue to the file (set a delay for the operation of writing the file to simulate the performance bottleneck).

3. The message server acts as a buffer between the console and file writing.

Example code:

Note: adding messages to the message queue can be added at one time through the for loop. In order to observe the changes of files and queues, this paper adopts console input. The actual speed of writing a line of file records should be higher than the hand speed. Therefore, the thread sleep time is added in this example.

summary

The above is all about the asynchronous mechanism in this article. The comments in the example code are still relatively detailed. If you have any questions, you can leave a message. Xiaobian will reply to you in time. At the same time, thank you for your support!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>