forked from Kotlin-Polytech/FromKotlinToJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
63 lines (59 loc) · 2.04 KB
/
Copy pathMain.java
File metadata and controls
63 lines (59 loc) · 2.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
53
54
55
56
57
58
59
60
61
62
63
package part4.deadlock;
import java.util.ArrayList;
import java.util.List;
public class Main {
private static final List<Integer> listA = new ArrayList<>();
private static final List<Integer> listB = new ArrayList<>();
public static void main(String[] args) {
Thread second = new Thread(() -> {
int i = 0;
while (i < 1000) {
try {
synchronized (listA) {
System.out.println("Second thread locks listA");
i++;
Thread.sleep(100);
listA.add(i);
synchronized (listB) {
System.out.println("Second thread locks listB");
i++;
listB.add(i);
}
}
System.out.println("Second thread unlocks lists, i=" + i);
Thread.sleep(100);
} catch (InterruptedException ex) {
break;
}
}
});
second.start();
int j = 0;
while (j < 1000) {
try {
synchronized (listB) {
System.out.println("First thread locks listB");
j++;
Thread.sleep(100);
listB.add(j);
synchronized (listA) {
System.out.println("First thread locks listA");
j++;
listA.add(j);
}
}
System.out.println("First thread unlocks lists, j=" + j);
Thread.sleep(100);
} catch (InterruptedException ex) {
break;
}
}
try {
second.join();
} catch (InterruptedException ex) {
System.out.println("Interrupted unexpectedly!");
}
System.out.println("listA = " + listA);
System.out.println("listB = " + listB);
}
}