生活随笔
收集整理的這篇文章主要介紹了
Synchronize读脏解决
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Synchronize讀臟解決
對于業(yè)務(wù)需要同步的
同時,添加Synchronize關(guān)鍵字
比如,在getValue/setValue方法上
都加上synchronize關(guān)鍵字
保證,業(yè)務(wù)的一致性
package com.bjsxt.base.sync004;
/*** 業(yè)務(wù)整體需要使用完整的synchronized,保持業(yè)務(wù)的原子性。**/
public class DirtyRead {private String username =
"bjsxt";
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.out.println(
"setValue最終結(jié)果:username = " + username +
" , password = " + password);}
public synchronized void getValue() {System.out.println(
"getValue方法得到:username = " +
this.username +
" , password = " +
this.password);}
public static void main(String[] args)
throws Exception {
final DirtyRead dr =
new DirtyRead();Thread t1 =
new Thread(
new Runnable() {
@Overridepublic void run() {dr.setValue(
"z3",
"456");}});t1.start();Thread.sleep(
1000);dr.getValue();}}
運(yùn)行
總結(jié)
以上是生活随笔為你收集整理的Synchronize读脏解决的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。