java并发编程学习之脏读代码示例及处理

public class Thread10 {
    public static void main(String[] args) {
        Thread10_Entity entity = new Thread10_Entity();
        Thread10_1 t10_1 = new  Thread10_1(entity);
        t10_1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(entity.get());

    }
}

class Thread10_1 extends Thread {
    private Thread10_Entity thread10_Entity;

    public Thread10_1(Thread10_Entity t10) {
        this.thread10_Entity = t10;
    }
    @Override
    public void run() {
        thread10_Entity.set("admin", "admin");
    }
}
class Thread10_Entity {
    private String username = "user";
    private String password = "user";

    synchronized void set(String username, String password) {
        this.username = username;
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.password = password;
    }
    String get() {
        return username + "   " + password;
    }
}

运行结果:admin user

加上sleep只是为了放大错误,便于观察。
有任何疑问欢迎留言或者加企鹅群(282034885)讨论

那么如何避免脏读呢?上篇文章( java并发编程学习之一段简单代码证明synchronized锁的是对象)中提到过,synchronized锁的是对象,这里就可以用上了。
在get方法上加上synchronized关键字即可,在set没处理完之前,对对象加锁,避免其他线程进行脏读。

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页