运行主程序
public class ThreadTest {
volatile int p = 0, q = 0;
public void test() throws InterruptedException {
Thread writeThread = new Thread(){
public void run(){
while (!isInterrupted()) {
p++;
q++;
}
}
};
Thread readThread = new Thread(){
public void run(){
while (!isInterrupted()) {
//p should not be less than q
if(p<q){
System.out.println("happen before violation p = " + p + ";q = " + q);
}
}
}
};
writeThread.start();
readThread.start();
Thread.currentThread().sleep(2);
writeThread.interrupt();
readThread.interrupt();
}
public static void main(String[] args) throws InterruptedException {
new ThreadTest().test();
}
}
输出
在违规之前发生 p = 736;q = 827
在违规之前发生 p = 4635;q = 4657
在违规之前发生 p = 6421;q = 6440
在违规之前发生 p = 8719;q = 8803