File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Chapter_30/exercise_30_10 Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments