次のコードは、Windows 7 x86 jdk 7 (-ea をオン)で volatile の JLS の例に従って AssertionError をスローすべきではありませんか?
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();
}
}
};