Java多线程同步方法Synchronized和volatile

11 同步方法
 synchronized – 同时解决了 有序性、可见性问题
 volatile – 结果 可见性问题
12 同步- synchronized
synchronized可以在 任意对象上加锁,而加锁的这段代码将成为 互斥区临界区
每个对象都可以做为锁,但一个对象做为锁时,应该被 多个线程共享,这样显得有意义。
注:见code
13 一个线程执行临界区代码过程如下: 1. 获得同步锁 2. 清空工作内存 3. 从主存拷贝变量副本到工作内存 4. 对这些变量计算 5. 将变量从工作内存写回到主存 6. 释放锁
14  多线程 – 同步- synchronized
 在什么对象上加锁 ?
 代码块 : 指定的对象
 方法上 : this引用(就是说这个对象示例同一个时间只能够有1个线程访问)
 静态方法上 : class对象
15 多线程 – 同步- volatile 
 volatile : JAVA提供的一种 轻量级同步工具,用于保证一个字段的 可见性, 但是并 不保证顺序性
 适合的场景:状态真正独立于程序内其他内容时才能使用 volatile (有一个线程发布状态)
 eg : 状态标志,边界值等
 1 import java.util.ArrayList;

 2 

 3 public class Account {

 4     private int money;

 5 

 6     public Account(int money) {

 7         this.money = money;

 8     }

 9 

10     // 方法上 : this引用

11     public synchronized void saveMoney(int money) {

12         this.money += money;

13     }

14 

15     public synchronized void getMoney(int money) {

16         this.money -= money;

17     }

18 

19     public synchronized void showMoney() {

20         System.out.println(money);

21     }

22 

23     static class SaveThread extends Thread {

24         Account account;

25         static Integer code = 100;

26 

27         public SaveThread(Account account) {

28             this.account = account;

29         }

30 

31         public void run() {

32             for (int i = 0; i < 50; i++) {

33                 // 代码块 : 指定的对象

34                 synchronized (code) {

35                     code++;

36                 }

37                 account.saveMoney(1000);

38                 System.out.println("sava i:" + i + " code:" + code);

39                 try {

40                     Thread.currentThread().sleep(1);

41                 } catch (InterruptedException e) {

42                     e.printStackTrace();

43                 }

44             }

45             for (int i = 0; i < 50; i++) {

46                 // 代码块 : 指定的对象

47                 synchronized (code) {

48                     code--;

49                 }

50                 account.getMoney(1000);

51                 System.out.println("get i:" + i + " code:" + code);

52                 try {

53                     Thread.currentThread().sleep(1);

54                 } catch (InterruptedException e) {

55                     e.printStackTrace();

56                 }

57             }

58         }

59     }

60 

61     public static void main(String[] args) throws Exception {

62         Account account = new Account(1000);

63         ArrayList<SaveThread> st = new ArrayList<Account.SaveThread>();

64         for (int i = 0; i < 4; i++) {

65             st.add(new SaveThread(account));

66             st.get(i).start();

67         }

68         Thread.currentThread().sleep(1000);

69         account.showMoney();

70         System.out.println(st.get(0).code);

71     }

72 }
View Code

 

你可能感兴趣的:(synchronized)