脏读
例子程序:
package com.lhy.thread01; public class DirtyRead { private String username = "lhy"; 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.err.println(Thread.currentThread().getName()+":setValue最终结果:username = " +username +" , password = "+password); } //synchronized public void getValue(){ System.err.println(Thread.currentThread().getName()+":getValue方法得到:username = "+username+", password="+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("zhangsan", "456"); } },"t1"); t1.start(); Thread.sleep(1000); dr.getValue(); } }
打印结果:
t1线程先对username设置值,将初始值 lhy 修改为 zhangsan ,然后睡眠1秒,此时 password还是初始值 123,所以主线程在1秒的时候读取到的username是修改后的zhangsan,password是初始值123,等到2秒时,t1线程将password修改为456,t1线程执行结束。打印username=zhangsan 、password=456。
要想保证读写业务的一致性,getValue也应该加上synchornized关键字。加上之后打印的结果就是我们预期的: