Help me figure this code out. (Reciprocal locking)



  • Hi, I understand correctly that the first thread starts, and since the code is read in sequence, the first thread starts up, so we're going to make a mistake, and then the second thread starts?

    public static void main(String[] args) throws InterruptedException {
            t1.start();
            t1.interrupt()
            t2.start();
        }
        public static class T1 extends Thread {@
            Override
            public void run() {
                try {
                    t2.join();
                    System.out.println("T1 finished");
                } catch (InterruptedException e) {
                    System.out.println("T1 was interrupted");
                }
            }
        }
        public static class T2 extends Thread {@
            Override
            public void run() {
                try {
                    t1.join();
                    System.out.println("T2 finished");
                } catch (InterruptedException e) {
                    System.out.println("T2 was interrupted");
                }
            }
        }
    }
    


  • Your code, as you brought it, does not contain a deadlock. (I assume variables t1 and t2 are objects of types T1 and T2 respectively.)

    We'll see the flow. t1♪ He can only expect t2.join();♪ If he stops to wait there, the main flow will sooner or later be completed (or has already been completed) t1.interrupt()which will lead to a withdrawal of expectations, an exemption and the completion of this flow.

    Now, flow t2♪ He can only wait. t1.join();, as we see, t1 It's over, so the challenge is over. join() It's over.

    If you have a deadlock, it's somewhere else.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2