-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
40 lines (33 loc) · 701 Bytes
/
Copy pathMain.java
File metadata and controls
40 lines (33 loc) · 701 Bytes
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
package b;
class AddThread extends Thread {
public void run(){
for (int i = 0; i < Main.LOOP; i++){
synchronized (Main.LOCK) {
Main.count += 1;
}
}
}
}
class DecThread extends Thread {
public void run(){
for (int i = 0; i < Main.LOOP; i++){
synchronized (Main.LOCK) {
Main.count -= 1;
}
}
}
}
public class Main {
final static int LOOP = 10000;
public static int count = 0;
public static final Object LOCK = new Object();//静态变量作为锁
public static void main(String[] args) throws Exception {
Thread t1 = new AddThread();
Thread t2 = new DecThread();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count);
}
}