对于对象额同步异步方法,我们在设计自己的程序的时候,一定要考虑的问题整体,不然会出现数据不一致的错误,很经典的就是赃读(dityread)
?
package com.nbkj.thread;
public class DityRead {
private String username = "hsj179540";
private String password = "123";
public synchronized void setValue(String username, String password) {
this.username = username;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.password = password;
System.out.println("setValue的最终结果是:username:" + this.username + ",password:" + this.password);
}
/*synchronized */
public synchronized void getVlaue() {
System.out.println("getValue的最终结果是:username:" + this.username + ",password:" + this.password);
}
public static void main(String[] args) throws Exception {
final DityRead dityRead = new DityRead();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
dityRead.setValue("zs", "zsp");
}
}, "t1");
/*
* Thread t2 = new Thread(new Runnable() {
*
* @Override public void run() {
*
* } }, "t2");
*/
t1.start();
Thread.sleep(1000);
dityRead.getVlaue();
}
}
? 考虑问题的时候一定要考虑问题的整体性,当setValue执行的时候,不想getValue执行,所以getValue也要加锁,这样才能保证同步,不然可能引起赃读。
原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)、持久性(Durability)
当执行DML操作的时候,会记录你执行的旧值方便回滚。相当于Ctrl +Z
当回滚的时候找不到值,会报错snapshot too old
原文:https://www.cnblogs.com/bingshu/p/9321167.html