-
Notifications
You must be signed in to change notification settings - Fork 24
/
IteratorAccessor.java
56 lines (49 loc) · 1.19 KB
/
IteratorAccessor.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package study.javacon;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class IteratorAccessor {
public static void main(String[] args) {
final List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
Runnable addAction = new Runnable(){
@Override
public void run() {
add(list, 1);
sleep();
add(list, 2);
sleep();
add(list, 3);
sleep();
add(list, 4);
sleep();
}
private void add(final List<Integer> list, int i) {
list.add(i);
System.out.println("Add:" +i);
}
};
final Iterator<Integer> itr = list.iterator();
Runnable printAction = new Runnable(){
@Override
public void run() {
while(itr.hasNext()){
System.out.println(itr.next());
sleep();
}
}
};
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.execute(addAction);
pool.execute(printAction);
}
static void sleep() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}