-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCDonate.java
More file actions
53 lines (40 loc) · 1.04 KB
/
CDonate.java
File metadata and controls
53 lines (40 loc) · 1.04 KB
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
package example.ThreadExample.Concurrency;
public class CDonate {
private static int sum = 0;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i=0; i<3; i++) {
add(100);
}
});
Thread t2 = new Thread(() -> {
for (int i=0; i<3; i++) {
add(100);
}
});
t1.start();
t2.start();
// CPerson p1 = new CPerson();
// CPerson p2 = new CPerson();
// p1.start();
// p2.start();
}
public synchronized static void add(int n) {
int tmp = sum;
tmp = tmp + n;
try {
Thread.sleep((int)(1000 * Math.random()));
} catch(InterruptedException e) {
System.out.println(e.toString());
}
sum = tmp;
System.out.println("捐款總額= "+sum);
}
}
class CPerson extends Thread {
public void run() {
for (int i=1; i<=3; i++) {
CDonate.add(100);
}
}
}