-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSeparateLinkedList.java
More file actions
61 lines (51 loc) · 1.62 KB
/
SeparateLinkedList.java
File metadata and controls
61 lines (51 loc) · 1.62 KB
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
import java.util.*;
public class SeparateLinkedList {
static class Writer implements Runnable {
private LinkedList<Integer> list;
private Random rand = new Random();
private int id;
Writer(int id) {
this.list = new LinkedList<>();
this.id = id;
}
private int randomBoundedInt() {
return rand.nextInt(10001);
}
public void run() {
for (int i = 0; i < 1000; i++) {
int next = randomBoundedInt();
list.add(next);
System.out.printf("Thread #%d: %d\n", id, next);
}
}
}
public static void main(String[] args) {
int numThreads = 1;
if (args.length == 0) {
System.err.println("Usage: java SeparateLinkedList [num of threads]");
System.exit(1);
} else {
try {
numThreads = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Usage: java SeparateLinkedList [num of threads]");
System.exit(1);
}
}
List<Thread> threadPool = new ArrayList<>();
for (int i = 0; i < numThreads; i++) {
Writer w = new Writer(i);
threadPool.add(new Thread(w));
}
for (Thread t : threadPool) {
t.start();
}
for (Thread t : threadPool) {
try {
t.join();
} catch (InterruptedException e) {
System.err.println("Error encountered when trying to join");
}
}
}
}