Java multithreading Summary 4: Examples of volatile and synchronized

Source: Internet
Author: User

1. Synchronized ensures synchronization.

First, let's look at a class that generates an even number.

Package demo. thread;/*** this is an abstract class of the int generator **/public abstract class intgenerator {private volatile Boolean canceled = false; public abstract int next (); Public void cancel () {canceled = true;} public Boolean iscanceled () {return canceled ;}}


 

/** Generate an even number */class evengenerator extends intgenerator {private int currentevenvalue = 0; string S = ""; @ overridepublic int next () {synchronized (s) {++ currentevenvalue; + currentevenvalue; return currentevenvalue;} // You can also // public synchronized int next () {// + currentevenvalue; // ++ currentevenvalue; // return currentevenvalue ;//}}

Note that a synchronization lock is required when an even number is generated. Otherwise, thread 1 may have just executed a sentence + + currentevenvalue; the operation will be snatched from the CPU by thread 2, and thread 2 will execute the return currentevenvalue; in this case, an odd number is returned. Add synchronized
That is, two threads can only execute synchronized block code in one thread at the same time.

Test code:

Package demo. thread; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors;/** consumption Number */public class evenchecker implements runnable {private intgenerator generator; private final int ID; Public evenchecker (intgenerator g, int ident) {generator = g; id = ident;} public void run () {While (! Generator. iscanceled () {int val = generator. Next (); If (Val % 2! = 0) {// if it is not an even number of system. Out. println (Val + "not enen! "); Generator. cancel () ;}} public static void test (intgenerator GP, int count) {executorservice exec = executors. newcachedthreadpool (); For (INT I = 0; I <count; I ?#exec.exe cute (New evenchecker (GP, I); Exec. shutdown ();} public static void test (intgenerator GP) {test (GP, 10);} public static void main (string [] ARGs) {test (New evengenerator ());}}

Analysis: If the even number of classes is not added with synchronized, the test program will have an odd number and cause the program to exit.

 

2. Volatile indicates atomicity and visibility.

For variables shared between multiple threads, each thread has its own copy. When thread 1 changes the variable value, other threads do not immediately know that the variable value has changed, volatile ensures that the variable value is visible to each thread. A thread changes the value and the value in other threads changes immediately. Atomicity indicates that the operation cannot be interrupted, for example, assigning values to basic variables.

Sample Code:

Package demo. thread; public class volatiledemo implements runnable {private volatile int I = 0; // volatile sets the visibility public synchronized int getvalue () {return I;} private synchronized void enenincrement () {I ++; I ++ ;}@ overridepublic void run () {While (true) enenincrement () ;}public static void main (string [] ARGs) {volatiledemo at = new volatiledemo (); New thread (). start (); While (true) {int val =. getvalue () ; If (Val % 2! = 0) {// returns an odd number. Exit the program system. Out. println (Val + "is not enen! "); System. Exit (0 );}}}}

Note that the I ++ operation is not an atomic row operation, and synchronized must be added to the getvalue () method.

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.