-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSyncCollections.java
39 lines (32 loc) · 988 Bytes
/
SyncCollections.java
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
import java.util.*;
public class SyncCollections {
public static void main(String[] args) throws InterruptedException {
ArrayList<String> names = new ArrayList<>();
List<String> synlist = Collections.synchronizedList(names);
synlist.add("Alex");
synlist.add("Max");
synlist.add("Elis");
synlist.add("Mike");
synlist.add("Tom");
Runnable run1 = () -> {
synchronized (synlist) {
Iterator<String> it = synlist.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
};
Runnable run2 = () -> {
synchronized (synlist) {
synlist.remove(1);
}
};
Thread th1 = new Thread(run1);
Thread th2 = new Thread(run2);
th1.start();
th2.start();
th1.join();
th2.join();
System.out.println(synlist);
}
}