-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayMultiThreadAccess.java
executable file
·83 lines (58 loc) · 2.18 KB
/
ArrayMultiThreadAccess.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
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.*;
import java.util.concurrent.CountDownLatch;
/**
* Created with IntelliJ IDEA.
* User: Amine
* Date: 9/10/13
* Time: 7:34 PM
* To change this template use File | Settings | File Templates.
*/
public class ArrayMultiThreadAccess {
private List<String> strings = new ArrayList<String>();
private Random rnd = new Random();
private int numWorkers;
private CountDownLatch countDownLatch;
public static void main(String[] args) {
ArrayMultiThreadAccess target = new ArrayMultiThreadAccess(Runtime.getRuntime().availableProcessors() - 1, 25);
try {
target.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void await() throws InterruptedException {
countDownLatch.await();
}
public ArrayMultiThreadAccess(int numWorkers, long timeToFillUp) {
this.numWorkers = numWorkers;
countDownLatch = new CountDownLatch(numWorkers);
long t = System.currentTimeMillis() + timeToFillUp;
while (System.currentTimeMillis() < t) {
strings.add("" + Math.abs(rnd.nextInt()));
Thread.currentThread().yield();
}
System.out.println("Filled up array w/ " + strings.toArray().length + " items.");
for (int i = 0; i < numWorkers; i++) {
new Thread(new WorkerThread(i)).start();
}
}
class WorkerThread implements Runnable {
private int threadId;
private int workedOn = 0;
private WorkerThread() { throw new IllegalStateException(); }
WorkerThread(int threadId) {
this.threadId = threadId;
}
@Override
public void run() {
String[] arr = {};
arr = strings.toArray(arr);
for (int i = threadId; i < arr.length; i = i + numWorkers) {
System.out.println("Thread " + threadId + " " + arr[i]);
workedOn++;
}
System.out.println("Thread " + threadId + " processed " + workedOn + " recs.");
countDownLatch.countDown();
}
}
}