Java multi-threaded Development seven--thread-safe data structure __arcinfo
Source: Internet
Author: User
volatile VariableThe volatile variable indicates that it must be consistent with the main memory, which is actually a "synchronization of the variables", meaning that the operation of the volatile variable is atomic, such as before a long or double variable. Variables in the Java language are saved in main memory and can be used for communication between multithreading, and each thread has its own working memory. Volatile is used to ensure that this variable is synchronized between the main memory and the working memory of the thread. public class sample{int i; volatile Int J; ......... } In the example above, when one thread changes the value of I, the value of I that is read by another thread may not be the changed value, because the value that the thread has changed in working memory may not have been synchronized to the main memory. This problem does not exist on the variable J, because volatile guarantees the synchronization of J from the working memory of the thread to the main memory. JDK1.5 provides data structure after a bunch of atomic variables, a variety of thread-safe List, Queue, MAP, etc., not one description, you can see the JDK documentation. Demonstrate it with a producer/consumer model. public class Blockqueuesample ... {
Blockingqueue < string > resource = new Linkedblockingqueue < string > (10);
Atomicinteger i = new Atomicinteger ();
Boolean exit = FALSE;
Public Blockqueuesample () ... {
Thread consumer = new Thread (new consumer ());
Thread producer = new Thread (new producer ());
Consumer.start ();
Producer.start ();
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service