Why does this Java program terminate despite that apparently it shouldn't (and didn't)?

前端 未结 5 1983
天涯浪人
天涯浪人 2020-12-02 03:24

A sensitive operation in my lab today went completely wrong. An actuator on an electron microscope went over its boundary, and after a chain of events I lost $12 million of

5条回答
  •  忘掉有多难
    2020-12-02 04:10

    You could use an object to synchronize the writes and reads. Otherwise, as others said before, a write to currentPos will occur in the middle of the two reads p.x+1 and p.y.

    new Thread() {
        void f(Point p) {
            if (p.x+1 != p.y) {
                System.out.println(p.x+" "+p.y);
                System.exit(1);
            }
        }
        @Override
        public void run() {
            while (currentPos == null);
            while (true)
                f(currentPos);
        }
    }.start();
    Object sem = new Object();
    while (true) {
        synchronized(sem) {
            currentPos = new Point(currentPos.x+1, currentPos.y+1);
        }
    }
    

提交回复
热议问题