Java多线程之对写业务加锁,对读业务不加锁,会产生脏读

 1 import java.util.concurrent.TimeUnit;
 2 
 3 /**
 4  * 对写业务加锁
 5  * 对读业务不加锁
 6  * 脏读
 7  */
 8 public class Account {
 9 
10     String name;
11     double balance;
12 
13     public synchronized void set(String name, double balance) {
14         this.name = name;
15         try {
16             Thread.sleep(2000); //写线程休眠两秒
17         } catch (InterruptedException e) {
18             e.printStackTrace();
19         }
20         this.balance = balance;
21     }
22 
23     /**
24      * 解决脏读在方法上加synchronized
25      * @param name
26      * @return
27      */
28     public /*synchronized*/ double getBalance(String name) {
29         return this.balance;
30     }
31 
32     public static void main(String[] args) {
33 
34         Account account = new Account();
35         new Thread(() -> account.set("张三", 100.0)).start();
36 
37         try {
38             TimeUnit.SECONDS.sleep(1); //读线程休眠一秒
39         } catch (InterruptedException e) {
40             e.printStackTrace();
41         }
42 
43         System.out.println(account.getBalance("张三"));
44 
45         try {
46             TimeUnit.SECONDS.sleep(2); //读线程休眠两秒
47         } catch (InterruptedException e) {
48             e.printStackTrace();
49         }
50 
51         System.out.println(account.getBalance("张三"));
52 
53     }
54 
55 }

 

posted @ 2020-01-31 19:48  尘世间迷茫的小书童  阅读(702)  评论(0编辑  收藏  举报