-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathProblem$10.java
70 lines (65 loc) · 1.94 KB
/
Problem$10.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package chapter_thirty_two;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* *32.10 (Use synchronized sets) Using synchronization, correct the problem
* in the preceding exercise so that the second thread does not throw a
* ConcurrentModificationException.
*
*
* @author Sharaf Qeshta
* */
public class Problem$10
{
public static void main(String[] args)
{
Set<Object> set = Collections.synchronizedSet(new HashSet<>());
// adding a number to the set every second
new Thread( () ->
{
while (true)
{
try
{
synchronized (set)
{
set.add(set.size()+1);
}
Thread.sleep(1000);
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}).start();
// traverse the set back and forth every second
new Thread( () ->
{
while (true)
{
try
{
synchronized (set)
{
Iterator<Object> setIterator = set.iterator();
while (setIterator.hasNext())
System.out.print(setIterator.next() + " ");
System.out.println();
Object[] objects = set.toArray();
for (int i = objects.length-1; i > -1; i--)
System.out.print(objects[i] + " ");
System.out.println();
}
Thread.sleep(1000);
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}).start();
}
}