8. 8
• 正しく同期しないと、結果を推測するのは難しいという簡単な並行プログラム
public class PossibleReordering {
static int x = 0;
static int y = 0;
static int a = 0;
static int b = 0;
public static void main(String rags[]) throws InterruptedException {
Thread one = new Thread(new Runnable() {
@Override
public void run() {
a = 1;
x = b;
}
});
Thread other = new Thread(new Runnable() {
@Override
public void run() {
b = 1;
y = b;
}
});
one.start();
other.start();
one.join();
other.join();
System.out.println("(" + x + "," + y + ")");
}
12. 12
同期化の相乗りの例
private final class Sync extends AbstractQueuedSynchronizer {
private static final int RUNNING = 1;
private static final int RAN = 2;
private static final int CANCELLED = 4;
private V result;
private Exception exception;
void innerSet(V v) {
while (true) {
int s = getState();
if (ranOrCancelled(s)) {
return;
}
if (compareAndSetState(s, RAN)) {
break;
}
result = v;
releaseShared(0);
done();
}
V innerGet() throws InterruptedException, ExecutionException {
acquireSharedInterruptibly(0);
if (getState() == CANCELLED) {
throw new CancellationException();
}
if (exception != null) {
throw new ExecutionException(exception);
}
return result;
}
}