-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSeparateWrite.java
More file actions
70 lines (59 loc) · 1.91 KB
/
SeparateWrite.java
File metadata and controls
70 lines (59 loc) · 1.91 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
62
63
64
65
66
67
68
69
70
import java.util.*;
import java.nio.charset.Charset;
public class SeparateWrite {
static class Writer implements Runnable {
private Map<Integer, String> map;
private Random rand = new Random();
private int id;
Writer(int id) {
this.map = new HashMap<>();
this.id = id;
}
private String randomString() {
byte[] array = new byte[10];
rand.nextBytes(array);
String randomString = new String(array, Charset.forName("ASCII"));
return randomString;
}
private int randomBoundedInt() {
return rand.nextInt(10001);
}
public void run() {
for (int i = 0; i < 1000; i++) {
int idx = randomBoundedInt();
String item = randomString();
map.put(idx, item);
System.out.printf("%d: %s\n", idx, item);
}
}
}
public static void main(String[] args) {
int numThreads = 1;
if (args.length == 0) {
System.err.println("Usage: java SeparateWrite [num of threads]");
System.exit(1);
} else {
try {
numThreads = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Usage: java SeparateWrite [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");
}
}
}
}