java-Multithreading in-depth (ii) mutex and visibility

Source: Internet
Author: User
Tags visibility

(i) Mutual exclusion

Mutex, or atomicity. Atoms, refers to the smallest matter, the specific non-division of the.

In CPU operation, the time slice of multi-threading is executed, and one block executes, which satisfies the atomicity of mutex.

Ways to guarantee mutex in Java:

1. Lock the program block with sychronized and implement mutual exclusion

Synchronized (lock) {      a++;}

2. Use atomic to implement mutual exclusion of variable operations

Public final static Atomicinteger Test_integer = new Atomicinteger (1);            public static void Main (String []args) throws Interruptedexception {          final Thread []threads = new thread[20];           for (int i = 0; i <; i++) {               final int num = i;               Threads[i] = new Thread () {public                   void run () {                     int now = Test_integer.incrementandget ();                      System.out.println ("I am Thread:" + num + ", I get the value, the added value is:" + now);                   }               ;               Threads[i].start ();           }           for (Thread t:threads) {               t.join ();           }           System.out.println ("Final run Result:" + test_integer.get ());      }  
Test_integer in multithreaded operations, the final result is not biased.

The JDK's documentation says: "The design atom class is used primarily as a variety of blocks for implementing non-blocking data structures and related infrastructure classes. The Compareandset () method is not a regular replacement method for locking. Apply it only if the object's important update is limited to a single variable.


(ii) visibility

CPU and memory speed is too high, the introduction of caching (cache, register, etc.); a thread consists of a thread ID, a command counter PC, a collection of registers, and a stack, as described in "programmer self-accomplishment".

Each thread has its own working memory, modifies the value of the process's main memory, needs to be copied to the working memory after the modification, and then writes back, other threads may appear, reading the dirty data to the non-writeback situation.

/** * Multithreaded Visibility Test *  * @author Peter_wang * @create-time 2015-1-12 pm 3:56:29 */public class Threadvisabledemo {    privat e static int a = 0;    Static class Getnumthread        extends Thread {        @Override public        void Run () {            System.out.println (a);//b1        }    }    Static class Changenumthread        extends Thread {        @Override public        void Run () {            a = 1;//a1,a2        }< c15/>}    /**     * @param args     *    /public static void main (string[] args) {        getnumthread Getnumthread = new Getnumthread ();        Changenumthread changenumthread = new Changenumthread ();        Changenumthread.start ();//c1        Getnumthread.start ();//c2    }}
execution Result: output 0 or 1


A1 reads the data, writes to the thread a working memory write cache, does not necessarily refresh the value of a in the main memory in real-time, B1 may read the old data.

Ways to guarantee visibility in Java:

1. Lock the program block with sychronized and implement mutual exclusion

Static class Getnumthread        extends Thread {        @Override public        void Run () {            synchronized ( Threadvisabledemo.class) {                System.out.println (a);//B1            }}    }    static Class Changenumthread        extends Thread {        @Override public        void Run () {            synchronized (threadvisabledemo.class) {                a = 1 ;//A1,a2}}}    
2. Use volatile to ensure variable visibility

private static volatile int a = 0;
3. Use atomic to manipulate variables to achieve visibility


java-Multithreading in-depth (ii) mutex and visibility

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.