java併發程式設計學習之髒讀程式碼示例及處理
阿新 • • 發佈:2019-02-11
public class Thread10 {
public static void main(String[] args) {
Thread10_Entity entity = new Thread10_Entity();
Thread10_1 t10_1 = new Thread10_1(entity);
t10_1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(entity.get());
}
}
class Thread10_1 extends Thread {
private Thread10_Entity thread10_Entity;
public Thread10_1(Thread10_Entity t10) {
this.thread10_Entity = t10;
}
@Override
public void run() {
thread10_Entity.set ("admin", "admin");
}
}
class Thread10_Entity {
private String username = "user";
private String password = "user";
synchronized void set(String username, String password) {
this.username = username;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.password = password;
}
String get() {
return username + " " + password;
}
}
執行結果:admin user
加上sleep只是為了放大錯誤,便於觀察。
有任何疑問歡迎留言或者加企鵝群(282034885)討論
那麼如何避免髒讀呢?上篇文章( java併發程式設計學習之一段簡單程式碼證明synchronized鎖的是物件)中提到過,synchronized鎖的是物件,這裡就可以用上了。
在get方法上加上synchronized關鍵字即可,在set沒處理完之前,對物件加鎖,避免其他執行緒進行髒讀。