一道面试题引发的思考

来源:互联网 发布:时代网络大厦租赁 编辑:程序博客网 时间:2024/04/27 22:31

最近看到这样一道java面试题,对于两年java工作的我竟也......

public class AtmoicTest {    private volatile long temp = 0;     public void set1() {        temp = 0;    }     public void set2() {        temp = -1;    }     public void check() {        System.out.println(temp);         if (0 != temp && -1 != temp) {            System.err.println("Error");        }    }public static void main(String[] args) {    final AtmoicTest v = new AtmoicTest();     // 线程 1:设置 temp = 0    final Thread t1 = new Thread() {        public void run() {            while (true) {                v.set1();            }        };    };    t1.start();     // 线程 2:设置 temp = -1    final Thread t2 = new Thread() {        public void run() {            while (true) {                v.set2();            }        };    };    t2.start();     // 线程 3:检查 0 != temp && -1 != temp    final Thread t3 = new Thread() {        public void run() {            while (true) {                v.check();            }        };    };    t3.start();}}

问题:会打印出 Error 么?或者有其它什么结果?

答案下期揭晓。


1 0