多线程-脏独
在我们设计程序的时候要考虑问题的整体,不然很容易出现脏读,看示例
public class DirtyRead { private String username = "bjsxt"; 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 = " + username + " , password = " + password); } public void getValue(){ System.out.println("getValue方法得到:username = " + this.username + " , password = " + this.password); } public static void main(String[] args) throws Exception{ final DirtyRead dr = new DirtyRead(); Thread t1 = new Thread(new Runnable() { @Override public void run() { dr.setValue("z3", "456"); } }); t1.start(); Thread.sleep(1000); dr.getValue(); } }
实际我们先要的结果应该是这样的:
二、数据库的ACID
这里先关注一下ORACLE的一致性读的特性:举个例子,有A和B两个人,A在上午9点的时候对一张很大的表进行查询操作,假设这个查询需要10分钟,B在9点05分的时候对A要查询的这条记录进行了DML操作,将原来的数据值为1改成了2,那么A在9点10分得到的结果一定是1,而不会是2.(做DML操作之前会把原来的值放到UNDO里,A拿到的是UNDO里的值,也有可能抛出snapshot too old异常,但绝不可能把2返回给A)