In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to use the variable data synchronized and volatile keywords about synchronous access sharing. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
The synchronized keyword ensures that only one thread can execute a method or a block of code at the same time.
It contains two features: 1, mutually exclusive 2, visible. That is, synchronization can not only prevent a thread from seeing that the object is in an inconsistent state, but also ensure that each thread that enters the synchronization method or synchronization code block sees all previous modifications protected by the same lock.
The java language specification guarantees that a variable is atomic when reading or writing, unless the variable is of type long or double.
Reading a variable that is not of type long or double ensures that the returned value is saved by a thread in the variable, even if multiple threads modify the variable concurrently without synchronization.
Although the language specification ensures that threads will not see arbitrary values when reading atomic data, it does not guarantee that values written by one thread are visible to another thread. Synchronization is necessary for reliable communication between threads and for mutually exclusive access.
Java code
Public class StopThread {private static boolean stopRequested = false; public static synchronized boolean isStopRequested () {return stopRequested;} public static synchronized void setStopRequested (boolean stopRequested) {StopThread.stopRequested = stopRequested } public static void main (String [] args) {try {new Thread (new Runnable () {@ Override public void run () {int I = 0) While (! isStopRequested ()) {System.out.println (iTunes +);}) .start (); TimeUnit.SECONDS.sleep (1) } catch (InterruptedException e) {e.printStackTrace ();} setStopRequested (true);}}
The above synchronized keyword is required, and without synchronization, the program will never be terminated: because there is no guarantee that the background thread will "see" the changes made by the main thread to the value of stopRequested, the background thread will always loop.
Note: both read and write methods must be synchronized, otherwise synchronization will not work.
StopRequested is atomic even if it is not synchronized, and these synchronization methods are for its communication effect, not for mutually exclusive access.
The volatile variable can be thought of as a "lighter synchronized"; the volatile variable requires less coding and less runtime overhead than the synchronized block, but what it can do is only part of the synchronized.
Locks provide two main features: mutual exclusion and visibility. Mutex means that only one thread is allowed to hold a specific lock at a time, so you can use this feature to implement a coordinated access protocol for shared data, so that only one thread at a time can use the shared data. Visibility is more complex, and it must ensure that changes made to shared data before releasing the lock are visible to another thread that subsequently acquires the lock-- without the visibility guarantee provided by the synchronization mechanism, the shared variable that the thread sees may be pre-modified or inconsistent values, which can cause many serious problems.
Volatile variables have the visibility properties of synchronized, but not atomic properties. This means that the thread can automatically discover the * value of the volatile variable. Volatile variables can be used to provide thread safety, but can only be applied to a very limited set of use cases: there are no constraints between multiple variables or between the current and modified values of a variable.
Java code
Public class StopThread2 {private static volatile boolean stopRequested = false; public static boolean isStopRequested () {return stopRequested;} public static void setStopRequested (boolean stopRequested) {StopThread2.stopRequested = stopRequested } public static void main (String [] args) {try {new Thread (new Runnable () {@ Override public void run () {int I = 0) While (! isStopRequested ()) {System.out.println (iTunes +);}) .start (); TimeUnit.SECONDS.sleep (1) } catch (InterruptedException e) {e.printStackTrace ();} setStopRequested (true);}}
Using volatile alone is not enough to implement counters. The problem is that the operator (+ +) is not atomic, for example
Java code
Private static volatile int nextSerialNumber = 0; public static int generaterSerialNumber () {return nextSerialNumber + +;}
It performs two operations in the nextSerialNumber field: first it reads the value and then writes back a new value, which is equivalent to the original value plus 1. If the second thread reads the field while the * * thread reads the old value and writes back the new value, the second thread will see the same value as the * * thread and return the same sequence number, and the program will calculate the error result.
One way to fix generaterSerialNumber is to remove the volatile and add the synchronized modifier from its declaration. This ensures that multiple calls do not cross access, ensuring that each call will see the effect of all previous calls.
The correction method of * is to use class AtomicLong.
Java code
Private static final AtomicLong nextSerialNumber = new AtomicLong (); public static long generaterSerialNumber () {return nextSerialNumber.getAndIncrement ();}
In short, when multiple threads share variable data, each thread reading or writing data must perform synchronization. Without synchronization, there is no guarantee that changes made by one thread will be known by another thread. If interactive communication between threads is required without mutual exclusion, the volatile modifier is an acceptable form, but it needs to be used correctly.
On "synchronous access to shared variable data synchronized and volatile keywords how to use" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.