我知道吧里cs大佬多
比如说要执行的是下面这个mode:
class UnsynchronizedState implements State {
private byte[] value;
private byte maxval;
UnsynchronizedState(byte[] v) { value = v; maxval = 127; }
UnsynchronizedState(byte[] v, byte m) { value = v; maxval = m; }
public int size() { return value.length; }
public byte[] current() { return value; }
public boolean swap(int i, int j) {
if (value[i] <= 0 || value[j] >= maxval) {
return false;
}
value[i]--;
value[j]++;
return true;
}
}
然后有这一段
class SwapTest implements Runnable {
private int nTransitions;
private State state;
SwapTest(int n, State s) {
nTransitions = n;
state = s;
}
public void run() {
int n = state.size();
if (n != 0)
for (int i = 0; i < nTransitions; ) {
int a = ThreadLocalRandom.current().nextInt(0, n);
int b = ThreadLocalRandom.current().nextInt(0, n - 1);
if (a == b)
b = n - 1;
if (state.swap(a, b)) {
i++;
}
}
}
最后有这么一段
private static void dowork(int nThreads, int nTransitions, State s)
throws InterruptedException {
Thread[] t = new Thread[nThreads];
for (int i = 0; i < nThreads; i++) {
int threadTransitions =
(nTransitions / nThreads
+ (i < nTransitions % nThreads ? 1 : 0));
t[i] = new Thread (new SwapTest (threadTransitions, s));
}
long start = System.nanoTime();
for (int i = 0; i < nThreads; i++)
t[i].start ();
for (int i = 0; i < nThreads; i++) {
System.out.println("x"+i);
t[i].join ();
}
long end = System.nanoTime();
double elapsed_ns = end - start;
System.out.format("Threads average %g ns/transition\n",
elapsed_ns * nThreads / nTransitions);
}
机制是这一段
you will use a simple prototype that manages a data structure that represents anarray of integers. Each integer is in the range [0,maxval] where maxval is at most 127, so the integer can be represented by the Java type byte. A statetransition, called a swap, consists of subtracting 1 from one of the positive integers in the array, and adding 1 to an integer that is less than maxval. Thesum of all the integers should therefore remain constant; if it varies, that indicates that one or more transitions weren't done correctly. Also, the values inthe array should always be in range.
谁有时间的话就帮我看看吧