4.髒讀

對於對象的同步、異步的方法,設計程序的時候必定要考慮問題的總體,出現數據不一致就一個經典的錯誤。

   
   
   
   
   
  1. 正確結果輸出:private synchronized void getUserValue()
  2. setValue 最終結果->:user = testuser pwd = 111111 getUserValue 設置值:user = testuser pwd = 111111

  3. 錯誤結果輸出:private void getUserValue() 屬於異步調用
  4. getUserValue 設置值:user = testuser pwd = 123456 setValue 最終結果->:user = testuser pwd = 111111
package demo1;/** * * Created by liudan on 2017/6/3. */public class MyThread4 { private String user = "liudan"; private String pwd = "123456"; private synchronized void setUserValue(String user, String pwd) { this.user = user; try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } this.pwd = pwd; System.err.println("setValue 最終結果->:user = " + user + "\t" + "pwd = " + pwd); } private void getUserValue() { System.err.println("getUserValue 設置值:user = " + this.user + "\t" + "pwd = " + this.pwd); } /** * 對一個方法枷加鎖,須要考慮功能業務的總體性,同時爲set、get加鎖,使用 synchronized 關鍵字,保證業務的原子性,否則則會出現業務的錯誤。 * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { final MyThread4 tUser = new MyThread4(); Thread userThread = new Thread(new Runnable() { @Override public void run() { tUser.setUserValue("testuser","111111"); } }); userThread.start(); Thread.sleep(1000); tUser.getUserValue(); }}
相關文章
相關標籤/搜索