版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xhd731568849/article/details/88902430
public class Test6 {
private double account;
private String name;
public synchronized void set(double account , String name){
this.name = name;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.account = account;
}
public double getAccount(){
return this.account;
}
public static void main(String[] args) {
Test6 t = new Test6();
new Thread(()->t.set(100.0,"abc")).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getAccount());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getAccount());
}
}
问1:加锁只对写方法加锁就万无一失了吗?
上述代码对set方法设置为同步,指的是某个线程执行set方法时,其他线程不能再同时执行set方法了。 set方法中的睡2秒钟是放大了线程执行时的时间差,为了让问题更突显而已。
尽管在set方法设置为同步,但共享的数据可能被非同步方法访问到。当new的线程执行完 this.name = name 后 , 此时主线程去调用 t.getAccount(),那么拿到的结果是还未设置account的值;等 new的线程 执行完 this.account = account后,此时主线程再去调用t.getAccount(),就会拿到新的值。产生脏读。(读到了还没有写完的数据)
解决:看具体业务需要
如果允许脏读,就不管了。
如果不允许脏读,则将getAccount 设置为 synchronized