对于对象的同步和异步的方法,设计程序的时候,一定要考虑问题的整体,不然就会出现数据不一致的错误,很经典的错误就是脏读(dirtyread)
示例
- public class Demo4 {
- private String username = "zhangsan";
- private String password = "123";
- public synchronized void setValue(String username, String password) {
- this.username = username;
- try {
- Thread.sleep(2000);
- } catch (Exception e) {
- e.printStackTrace();
- }
- this.password = password;
- System.out.println("setValue结果: username = " + username + ", password = " + password);
- }
- public void getValue() {
- System.out.println("getValue得到结果: username = " + this.username + ", password = " + this.password);
- }
- public static void main(String[] args) throws InterruptedException {
- final Demo4 demo4 = new Demo4();
- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run() {
- demo4.setValue("lisi", "567");
- }
- });
- t1.start();
- Thread.sleep(1000);
- demo4.getValue();
- }
- }
结果:
我们希望的结果应该是:lisi,567,这里就出现了脏读。
如将 getValue 方法加上 synchronized,效果如下:
在我们对于一个对象的方法加锁的时候,需要考虑业务的整体性,即为 setValue/getValue 方法同时加锁 synchronized 同步关键字,保证业务(service)的原子性,不然会出现业务错误(也从侧面保证业务的一致性)
来源: http://www.bubuko.com/infodetail-1979230.html