Java multithreading-Volatile keyword parsing, multithreading-volatile

Source: Internet
Author: User

Java multithreading-Volatile keyword parsing, multithreading-volatile

The volatile keyword can be analyzed from these three aspects: What is the atomicity of the program, what is the visibility of the program, and what is the orderliness of the program

What is the atomicity of a program?

Which of the following statements are atomic operations?

Public class ThreadCounter implements Runnable {private int count = 0; @ Override public void run () {++ count; // count ++ ;} public static void main (String [] args) throws InterruptedException {ThreadCounter thread = new ThreadCounter (); for (int I = 0; I <10000; I ++) {new Thread (thread ). start ();} Thread. sleep (1000); // ensure that the thread has finished running the System. out. println (thread. count );}}
View Code

Demo result: the first and second statements are non-atomic operations, and the third and fourth statements are atomic operations.

Run the command: The command code (count ++) of the javap-s-c ThreadCounterrun method: count ++ this line of code is divided into four commands for execution, which will be inconsistent in the case of multithreading.

Solution:

Public class ThreadCounter implements Runnable {private int count = 0; @ Override public void run () {synchronized (this) {++ count; // count ++ ;}} public static void main (String [] args) throws InterruptedException {ThreadCounter thread = new ThreadCounter (); for (int I = 0; I <10000; I ++) {new Thread (thread ). start ();} Thread. sleep (1000); // ensure that the thread has finished running the System. out. println (thread. count );}}
View Code what is program visibility?

 

Public class VolatileExample {boolean v = false; private void write () {v = true;} private void read () {while (! V) {} System. out. println ("program ended! ");} Public static void main (String [] args) throws InterruptedException {final VolatileExample example = new VolatileExample (); Thread thread1 = new Thread ()-> {example. read () ;}); thread1.start (); Thread. sleep (1000); Thread thread2 = new Thread ()-> {example. write () ;}); thread2.start ();}}
View Code demo result: the program has not ended. The v in the read method has not exited the loop because of the modification of the write method! Solution: add the volatile keyword to the variable v.
Public class VolatileExample {volatile boolean v = false; private void write () {v = true;} private void read () {while (! V) {} System. out. println ("program ended! ");} Public static void main (String [] args) throws InterruptedException {final VolatileExample example = new VolatileExample (); Thread thread1 = new Thread ()-> {example. read () ;}); thread1.start (); Thread. sleep (1000); Thread thread2 = new Thread ()-> {example. write () ;}); thread2.start ();}}
View Code

What is program orderliness?

 

Volatile Application Scenario 1. Number of status tags
public class ThreadTest {      private volatile boolean isContinue = false;            private class HandleThread extends Thread {            @Override            public void run() {                  while (isContinue) {                        // do something                  }            };      }}
View Code

2. double check

 

 

Summary:

Volatile can play a role in visibility and orderliness, but it cannot guarantee atomicity. It is a weak synchronization.

Synchronized ensures atomicity, visibility, and consistency.

 

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.