package com.wkcto.intrinsiclock;
/**
* 臟讀
* 出現(xiàn)讀取屬性值出現(xiàn)了一些意外, 讀取的是中間值,而不是修改之后 的值
* 出現(xiàn)臟讀的原因是 對(duì)共享數(shù)據(jù)的修改 與對(duì)共享數(shù)據(jù)的讀取不同步
* 解決方法:
* 不僅對(duì)修改數(shù)據(jù)的代碼塊進(jìn)行同步,還要對(duì)讀取數(shù)據(jù)的代碼塊同步
* Author: 老崔
*/
public class Test08 {
public static void main(String[] args) throws InterruptedException {
//開啟子線程設(shè)置用戶名和密碼
PublicValue publicValue = new PublicValue();
SubThread t1 = new SubThread(publicValue);
t1.start();
//為了確定設(shè)置成功
Thread.sleep(100);
//在main線程中讀取用戶名,密碼
publicValue.getValue();
}
//定義線程,設(shè)置用戶名和密碼
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屬性需要一定時(shí)間
} catch (InterruptedException e) {
e.printStackTrace();
}
this.pwd = pwd;
System.out.println(Thread.currentThread().getName() + ", setter --name:" + name + ", --pwd: " + pwd );
}
}
}