1 |
dl |
1.1 |
|
2 |
|
|
public class Finals { |
3 |
|
|
static int npairs = 2; |
4 |
|
|
static int iters = 10000000; |
5 |
|
|
static final int LEN = 4; |
6 |
|
|
static final Long[] nums = new Long[LEN]; |
7 |
|
|
static volatile boolean done; |
8 |
|
|
static volatile long total; |
9 |
|
|
|
10 |
|
|
public static void main(String[] args) { |
11 |
|
|
for (int i = 0; i < LEN; ++i) |
12 |
|
|
nums[i] = new Long(i+1); |
13 |
|
|
Thread[] ps = new Thread[npairs]; |
14 |
|
|
Thread[] as = new Reader[npairs]; |
15 |
|
|
for (int i = 0; i < npairs; ++i) { |
16 |
|
|
ps[i] = new Writer(); |
17 |
|
|
as[i] = new Reader(); |
18 |
|
|
} |
19 |
|
|
for (int i = 0; i < as.length; ++i) { |
20 |
|
|
ps[i].start(); |
21 |
|
|
as[i].start(); |
22 |
|
|
} |
23 |
|
|
} |
24 |
|
|
|
25 |
|
|
static long nextRandom(long seed) { |
26 |
|
|
return (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1); |
27 |
|
|
} |
28 |
|
|
|
29 |
|
|
static long initialSeed(Object x) { |
30 |
|
|
return (System.currentTimeMillis() + x.hashCode()) | 1; |
31 |
|
|
} |
32 |
|
|
|
33 |
|
|
static class Writer extends Thread { |
34 |
|
|
public void run() { |
35 |
|
|
long s = initialSeed(this); |
36 |
|
|
int n = iters; |
37 |
|
|
while (!done && n-- > 0) { |
38 |
|
|
int k = (int)(s & (LEN-1)); |
39 |
|
|
int l = (k+1) & (LEN-1); |
40 |
|
|
nums[k] = new Long(s); |
41 |
|
|
nums[l] = new Long(s); |
42 |
|
|
s = nextRandom(s); |
43 |
|
|
if (s == 0) s = initialSeed(this); |
44 |
|
|
} |
45 |
|
|
done = true; |
46 |
|
|
total += s; |
47 |
|
|
} |
48 |
|
|
} |
49 |
|
|
|
50 |
|
|
static class Reader extends Thread { |
51 |
|
|
public void run() { |
52 |
|
|
int n = iters; |
53 |
|
|
long s = initialSeed(this); |
54 |
|
|
while (s != 0 && n > 0) { |
55 |
|
|
long nexts = nums[(int)(s & (LEN-1))].longValue(); |
56 |
|
|
if (nexts != s) |
57 |
|
|
--n; |
58 |
|
|
else if (done) |
59 |
|
|
break; |
60 |
|
|
s = nexts; |
61 |
|
|
} |
62 |
|
|
done = true; |
63 |
|
|
total += s; |
64 |
|
|
if (s == 0) |
65 |
|
|
throw new Error("Saw uninitialized value"); |
66 |
|
|
} |
67 |
|
|
} |
68 |
|
|
} |