public class Test {
public static void main(String[] args) throws Exception {
Executor executor = new Executor();
new Thread(executor::write).start();
new Thread(executor::read).start();
Thread.sleep(500000);
}
static class Executor {
private int MAX_TIMES = 10000;
private boolean hasValue = false;
void write() {
for (int i = 0; i < MAX_TIMES; i++) {
while (hasValue) {}
System.out.println("Write, " + i);
hasValue = true;
}
}
void read() {
for (int i = 0; i < MAX_TIMES; i++) {
while (!hasValue) {}
hasValue = false;
System.out.println("Read, " + i);
}
}
}
}
我有这么一段代码,原本目的是两个线程交换执行、write线程执行一次,read线程执行一次,但hasValue并不是volatile类型,所以会发生死锁
我有两个问题:
1. 如果读写都是cache line,那为什么不是刚执行就发生死锁,而是执行一会,大概会交替执行100次左右才死锁。
2. 输出结果很奇怪,为什么不是write 0=> read 0 => write 1=>read 1.......这样下去,实际输出结果是这样的
Write, 0
Write, 1
Read, 0
Read, 1
Write, 2
Read, 2
Write, 3
Write, 4
Read, 3
Read, 4
Write, 5
Write, 6
Read, 5
Read, 6
Write, 7
Write, 8
Read, 7
Read, 8
Write, 9
Write, 10
Read, 9
Read, 10
Write, 11
Write, 12