下面的代码应该不会在Windows 7 x86 jdk 7上引发AssertionError(每个JLS example for volatile带有-ea开启)?挥发性jls示例
public class TestVolatile {
static volatile int i = 0;
static volatile int j = 0;
static void one() {
i++;
j++;
assert (i>=j);
//:"one: i=" + i + " j=" + j;
}
static void two() {
//System.out.println("i=" + i + " j=" + j);
assert (i<=j);
/*
System.out.print("<i=" + i);
for (int k = 0; k < 1000000; k++);
System.out.println(", j=" + j+">");
*/
}
public static final int NUM_WORKERS = 4;
public static void main (String [] args) {
final Worker [] workers = new Worker[NUM_WORKERS];
final Thread [] workerThreads = new Thread[NUM_WORKERS];
for (int i = 0; i < NUM_WORKERS; i++) {
Worker w = new Worker(i);
workers[i] = w;
workerThreads[i] = new Thread(w,"workerThread_"+i);
}
for (int i = 0; i < NUM_WORKERS; i++) {
workerThreads[i].start();
}
}
}
final class Worker implements Runnable {
final int id;
volatile boolean notDone = true;
public Worker(int tid){
id = tid;
}
@Override
public void run() {
//System.out.println("worker start:" + id);
try {
while (notDone) {
if (id < TestVolatile.NUM_WORKERS - 1) {
TestVolatile.one();
} else {
TestVolatile.two();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
};
我几乎马上就会发现一个错误。 – assylias
你认为哪里出错,为什么?澄清 – exexzian
我也得到了错误,没有任何延迟,并可靠地如此。 –