How can a Java variable be different from itself?

前端 未结 10 1851
日久生厌
日久生厌 2020-11-29 16:14

I am wondering if this question can be solved in Java (I\'m new to the language). This is the code:

class Condition {
    // you can change in the main
    p         


        
10条回答
  •  暖寄归人
    2020-11-29 16:44

    I managed to get a Gotcha! from this:

    volatile Object a = new Object();
    
    class Flipper implements Runnable {
      Object b = new Object();
    
      public void run() {
        while (true)  {
          Object olda = a;
          a = b;
          a = olda;
        }
      }
    
    }
    
    public void test() {
      new Thread(new Flipper()).start();
    
      boolean gotcha = false;
      while (!gotcha) {
        // I've added everything above this - I would therefore say still legal.
        if (a == a) {
          System.out.println("Not yet...");
        } else {
          System.out.println("Gotcha!");
          // Uncomment this line when testing or you'll never terminate.
          //gotcha = true;
        }
      }
    }
    

提交回复
热议问题