例子程序:ide
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(); } }
打印結果:this
t1線程先對username設置值,將初始值 lhy 修改成 zhangsan ,而後睡眠1秒,此時 password仍是初始值 123,因此主線程在1秒的時候讀取到的username是修改後的zhangsan,password是初始值123,等到2秒時,t1線程將password修改成456,t1線程執行結束。打印username=zhangsan 、password=456。spa
要想保證讀寫業務的一致性,getValue也應該加上synchornized關鍵字。加上以後打印的結果就是咱們預期的:線程