Skip to content

Commit 5682b4a

Browse files
committed
commit Exercise_30_10
1 parent 8609b5a commit 5682b4a

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package exercise_30_10;
2+
3+
import java.util.Collections;
4+
import java.util.HashSet;
5+
import java.util.Iterator;
6+
import java.util.Set;
7+
8+
public class Exercise_30_10 {
9+
private static Set set = Collections.synchronizedSet(new HashSet());
10+
11+
public static void main(String[] args) {
12+
Thread thread1 = new Thread(new AddToSetTask());
13+
Thread thread2 = new Thread(new TraverseSetTask());
14+
thread1.start();
15+
thread2.start();
16+
}
17+
18+
public static class AddToSetTask implements Runnable {
19+
20+
@Override
21+
public void run() {
22+
for(int i = 0; i < 1000000; i++) {
23+
System.out.println("AddToSetThread");
24+
set.add(i);
25+
try {
26+
Thread.sleep(1000);
27+
}
28+
catch (InterruptedException ex) {
29+
}
30+
}
31+
}
32+
}
33+
34+
public static class TraverseSetTask implements Runnable {
35+
36+
@Override
37+
public void run() {
38+
while(true) {
39+
System.out.println("TraverseSetThread");
40+
try {
41+
Thread.sleep(1000);
42+
}
43+
catch (InterruptedException ex) {
44+
}
45+
synchronized(set) {
46+
Iterator<Integer> iterator = set.iterator();
47+
while(iterator.hasNext()) {
48+
System.out.println(iterator.next());
49+
}
50+
}
51+
}
52+
}
53+
}
54+
}

0 commit comments

Comments
 (0)