package com.wkcto.intrinsiclock;
/**
* 臟讀
* 出現讀取屬性值出現了一些意外, 讀取的是中間值,而不是修改之后 的值
* 出現臟讀的原因是 對共享數據的修改 與對共享數據的讀取不同步
* 解決方法:
* 不僅對修改數據的代碼塊進行同步,還要對讀取數據的代碼塊同步
* Author: 老崔
*/
public class Test08 {
public static void main(String[] args) throws InterruptedException {
//開啟子線程設置用戶名和密碼
PublicValue publicValue = new PublicValue();
SubThread t1 = new SubThread(publicValue);
t1.start();
//為了確定設置成功
Thread.sleep(100);
//在main線程中讀取用戶名,密碼
publicValue.getValue();
}
//定義線程,設置用戶名和密碼
static class SubThread extends Thread{
private PublicValue publicValue;
public SubThread( PublicValue publicValue){
this.publicValue = publicValue;
}
@Override
public void run() {
publicValue.setValue("bjpowernode", "123");
}
}
static class PublicValue{
private String name = "wkcto";
private String pwd = "666";
public synchronized void getValue(){
System.out.println(Thread.currentThread().getName() + ", getter -- name: " + name + ",--pwd: " + pwd);
}
public synchronized void setValue(String name, String pwd){
this.name = name;
try {
Thread.sleep(1000); //模擬操作name屬性需要一定時間
} catch (InterruptedException e) {
e.printStackTrace();
}
this.pwd = pwd;
System.out.println(Thread.currentThread().getName() + ", setter --name:" + name + ", --pwd: " + pwd );
}
}
}