forked from shiyimin/androidtestdebug
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRaceConditionFix.java
More file actions
49 lines (43 loc) · 1.11 KB
/
RaceConditionFix.java
File metadata and controls
49 lines (43 loc) · 1.11 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
//
// 编译命令:
// javac -encoding UTF8 RaceConditionFix.java
//
public class RaceConditionFix {
private static int _sharedCounter = 0;
private synchronized static void dekker1() {
_sharedCounter++;
}
private synchronized static void dekker2() {
_sharedCounter++;
}
public static void main(String[] args) throws Exception {
if ( args.length != 1 ) {
System.out.println("使用方法: java RaceCondition <循环次数>");
return;
}
final int loopCount = Integer.parseInt(args[0]);
Thread thread1 = new Thread(new Runnable() {
public void run() {
for ( int i = 0; i < loopCount; ++i ) {
dekker1();
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
for ( int i = 0; i < loopCount; ++i ) {
dekker2();
}
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
int expected_sum = 2 * loopCount;
if ( _sharedCounter != expected_sum ) {
System.out.println(
String.format("资源竞争问题: 实际结果 $1%d 不等于期望结果 $2%d", _sharedCounter, expected_sum));
}
}
}