Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSeparateWrite.java
More file actions
Latest commit
70 lines (59 loc) · 1.91 KB
/
Copy pathSeparateWrite.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
importjava.util.*;
importjava.nio.charset.Charset;
publicclassSeparateWrite {
staticclassWriterimplementsRunnable {
privateMap<Integer, String> map;
privateRandomrand = newRandom();
privateintid;
Writer(intid) {
this.map = newHashMap<>();
this.id = id;
}
privateStringrandomString() {
byte[] array = newbyte[10];
rand.nextBytes(array);
StringrandomString = newString(array, Charset.forName("ASCII"));
returnrandomString;
}
privateintrandomBoundedInt() {
returnrand.nextInt(10001);
}
publicvoidrun() {
for (inti = 0; i < 1000; i++) {
intidx = randomBoundedInt();
Stringitem = randomString();
map.put(idx, item);
System.out.printf("%d: %s\n", idx, item);
}
}
}
publicstaticvoidmain(String[] args) {
intnumThreads = 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 (NumberFormatExceptione) {
System.err.println("Usage: java SeparateWrite [num of threads]");
System.exit(1);
}
}
List<Thread> threadPool = newArrayList<>();
for (inti = 0; i < numThreads; i++) {
Writerw = newWriter(i);
threadPool.add(newThread(w));
}
for (Threadt : threadPool) {
t.start();
}
for (Threadt : threadPool) {
try {
t.join();
} catch (InterruptedExceptione) {
System.err.println("Error encountered when trying to join");
}
}
}
}