Home  >  Q&A  >  body text

java - 线程同步为什么不一样

package com.dome;

public class Thread01 {

private volatile  static int a =10;
Thread td1 = new Thread(){
    
    public void run(){
        
        for(int i=0;i<3;i++){
            
                a = a+1;
            
            System.out.println(i+"td1:="+a);
        }
        
    }
    
};

Thread td2 = new Thread(){
    public void run(){
        
        for(int i=0;i<3;i++){
            a -=1;
            System.out.println(i+"td2:="+a);
        }
    }
    
};


public static void main(String[] args) {
    Thread01 th = new Thread01();
    th.td1.start();
    
    th.td2.start();
    
}

}

0td1:=9
0td2:=9
1td1:=10
1td2:=9
2td1:=10
2td2:=9

ringa_leeringa_lee2743 days ago475

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-18 10:56:18

    a = a + 1a = a - 1 Such a statement actually involves three operations: read-modify-write:

    1. Read the variable to a certain location on the stack

    2. Add (subtract) 1 to the value at this position in the stack

    3. Write the self-incremented value back to the storage location corresponding to the variable

    So while variable a uses volatile 修饰,但并不能使涉及上面三个操作的 a = a + 1a = a - 1具有原子性。为了保证同步性,需要使用 synchronized:

    public class Thread01 {
    
        private volatile static int a = 10;
    
        Thread td1 = new Thread() {
    
            public void run() {
    
                for (int i = 0; i < 3; i++) {
                    synchronized (Thread01.class) {
                        a = a + 1;
                        System.out.println(i + "td1:=" + a);
                    }
                }
            }
    
        };
    
        Thread td2 = new Thread() {
            public void run() {
    
                for (int i = 0; i < 3; i++) {
                    synchronized (Thread01.class) {
                        a -= 1;
                        System.out.println(i + "td2:=" + a);
                    }
                }
            }
    
        };
    
        public static void main(String[] args) {
            Thread01 th = new Thread01();
            th.td1.start();
    
            th.td2.start();
    
        }
    }

    The result of a certain operation:

    (Where td1 appears, a is +1; where td2 appears, a is -1)

    reply
    0
  • Cancelreply