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 运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/winterking3/article/details/83619091