1. 程式人生 > >Java多執行緒學習筆記(二) synchronized同步方法-防止髒讀

Java多執行緒學習筆記(二) synchronized同步方法-防止髒讀

1. 髒讀

在給一個物件賦值的時候進行了同步, 但是在取值的時候可能出現意外,此值已經被其他執行緒修改了,這種情況就是髒讀

1.1 PublicVar類

public class PublicVar {
    public String userName = "wang dong";
    public String password = "123456";

    public void getValue() {
        System.out.println("getValue: " + Thread.currentThread() + " userName = "
+ userName + " password = " + password); } public synchronized void setValue(String userName, String password) { try{ this.userName = userName; Thread.sleep(5000); this.password = password; System.out.println("setValue: " + Thread.currentThread
() + " userName = " + userName + " password = " + password); }catch (InterruptedException e){ e.printStackTrace(); } } }

1.2 ThreadA

public class ThreadA extends Thread{

    private PublicVar publicVar;

    public ThreadA(PublicVar publicVar){
        super();
        this
.publicVar = publicVar; } @Override public void run(){ super.run(); publicVar.setValue("B", "BB"); } }

1.3 Test

public class Test {
    public static void main(String[] args) {

        try {
            PublicVar value = new PublicVar();
            ThreadA threadA = new ThreadA(value);
            threadA.start();

            Thread.sleep(2000);

            value.getValue();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

1.4 執行結果

在這裡插入圖片描述
上圖展示的出現了髒讀

2. 避免髒讀

2.1 給get方法加synchronized

public class PublicVar {
    public String userName = "wang dong";
    public String password = "123456";

    public synchronized void getValue() {
        System.out.println("getValue: " + Thread.currentThread() + " userName = " + userName + " password = " + password);
    }

    public synchronized void setValue(String userName, String password) {
        try{
            this.userName = userName;
            Thread.sleep(5000);
            this.password = password;

            System.out.println("setValue: " + Thread.currentThread() + " userName = " + userName + " password = " + password);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}

2.2 執行結果

在這裡插入圖片描述