1 |
dl |
1.2 |
/* |
2 |
|
|
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
|
|
* Expert Group and released to the public domain, as explained at |
4 |
jsr166 |
1.5 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
dl |
1.2 |
*/ |
6 |
dl |
1.1 |
|
7 |
|
|
public class Finals { |
8 |
|
|
static int npairs = 2; |
9 |
|
|
static int iters = 10000000; |
10 |
|
|
static final int LEN = 4; |
11 |
|
|
static final Long[] nums = new Long[LEN]; |
12 |
|
|
static volatile boolean done; |
13 |
|
|
static volatile long total; |
14 |
|
|
|
15 |
|
|
public static void main(String[] args) { |
16 |
|
|
for (int i = 0; i < LEN; ++i) |
17 |
|
|
nums[i] = new Long(i+1); |
18 |
|
|
Thread[] ps = new Thread[npairs]; |
19 |
|
|
Thread[] as = new Reader[npairs]; |
20 |
|
|
for (int i = 0; i < npairs; ++i) { |
21 |
|
|
ps[i] = new Writer(); |
22 |
|
|
as[i] = new Reader(); |
23 |
|
|
} |
24 |
|
|
for (int i = 0; i < as.length; ++i) { |
25 |
|
|
ps[i].start(); |
26 |
|
|
as[i].start(); |
27 |
|
|
} |
28 |
|
|
} |
29 |
|
|
|
30 |
jsr166 |
1.3 |
static long nextRandom(long seed) { |
31 |
dl |
1.1 |
return (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1); |
32 |
|
|
} |
33 |
|
|
|
34 |
|
|
static long initialSeed(Object x) { |
35 |
|
|
return (System.currentTimeMillis() + x.hashCode()) | 1; |
36 |
|
|
} |
37 |
|
|
|
38 |
|
|
static class Writer extends Thread { |
39 |
|
|
public void run() { |
40 |
|
|
long s = initialSeed(this); |
41 |
|
|
int n = iters; |
42 |
|
|
while (!done && n-- > 0) { |
43 |
jsr166 |
1.4 |
int k = (int) (s & (LEN-1)); |
44 |
dl |
1.1 |
int l = (k+1) & (LEN-1); |
45 |
|
|
nums[k] = new Long(s); |
46 |
|
|
nums[l] = new Long(s); |
47 |
|
|
s = nextRandom(s); |
48 |
|
|
if (s == 0) s = initialSeed(this); |
49 |
|
|
} |
50 |
|
|
done = true; |
51 |
|
|
total += s; |
52 |
|
|
} |
53 |
|
|
} |
54 |
|
|
|
55 |
|
|
static class Reader extends Thread { |
56 |
|
|
public void run() { |
57 |
|
|
int n = iters; |
58 |
|
|
long s = initialSeed(this); |
59 |
|
|
while (s != 0 && n > 0) { |
60 |
jsr166 |
1.4 |
long nexts = nums[(int) (s & (LEN-1))].longValue(); |
61 |
jsr166 |
1.3 |
if (nexts != s) |
62 |
dl |
1.1 |
--n; |
63 |
|
|
else if (done) |
64 |
|
|
break; |
65 |
|
|
s = nexts; |
66 |
|
|
} |
67 |
|
|
done = true; |
68 |
|
|
total += s; |
69 |
jsr166 |
1.3 |
if (s == 0) |
70 |
dl |
1.1 |
throw new Error("Saw uninitialized value"); |
71 |
|
|
} |
72 |
|
|
} |
73 |
|
|
} |