多線程轉賬代碼示例
package com.concurrent.test4; import lombok.extern.slf4j.Slf4j; import java.util.Random; @Slf4j(topic = "c.test11:") /** *買票問題 */ public class Test15 { public static void main(String[] args) throws InterruptedException { //創建兩個賬戶相互轉賬,每人開始擁有1000快 Account a = new Account(1000); Account b = new Account(1000); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { //a給b轉賬1000次,每次金額隨機 a.transfer(b, randomAmount()); } }, "t1"); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { //b給a轉賬1000次,每次金額隨機 b.transfer(a, randomAmount()); } }, "t2"); t1.start(); t2.start(); t1.join(); t2.join(); // 查看轉賬2000次后的總金額 log.debug("total:{}",(a.getMoney() + b.getMoney())); } // Random 為線程安全 static Random random = new Random(); // 隨機 1~100 public static int randomAmount() { return random.nextInt(100) +1; } } class Account {//賬戶類 private int money;//初始化金額 public Account(int money) { this.money = money; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public synchronized void transfer(Account target, int amount) { //如果加synchronized還是不安全的,因為加在方法上等于保護的是自己的共享變量 //但是此處有兩個共享變量this.money和target.money //所以這兒應該用synchronized鎖住類對象,因為這倆共享變量是一個類中 synchronized (Account.class){ if (this.money > amount) { this.setMoney(this.getMoney() - amount); target.setMoney(target.getMoney() + amount); } } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
任務調度 多線程
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。