写加锁但读没有加锁造成的脏读问题

**
 * 对业务写方法加锁
 * 对业务读方法不加锁
 * 容易产生脏读问题 就是对写加锁但对读没有加锁,这样在写的过程中可能还没写完就被读了
 * 
 *
 */
public class Demo {
 String name;
 double balance;
 
 public synchronized void set(String name, double balance){
  this.name = name;
  try {
   Thread.sleep(2 * 1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  this.balance = balance;
 }
 
 public /*synchronized*/ double getBalance(String name){///*synchronized*/就是this对象与上面写加的锁是同一把 所以加了锁就能起到读写一体的作用
  return this.balance;
 }
 
 public static void main(String[] args) {
  Demo demo = new Demo();
  
  new Thread(()->demo.set("zhangsan",100.0)).start(); //JDK1.8新特性
  
  try {
   TimeUnit.SECONDS.sleep(1);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println(demo.getBalance("zhangsan"));
  
  try {
   TimeUnit.SECONDS.sleep(2);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println(demo.getBalance("zhangsan"));
 }
}
//结果是0.0 100.0  因为set方法中睡了两秒,所以第一次读是的double的默认值0.0