1

code is

    private static final MyThread myThread = new MyThread();

    public static void main(String[] args) {
        synchronized (myThread) {
            System.out.println("1");
            myThread.start();
            System.out.println("2");
            try {
                myThread.wait();
                System.out.println("3");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class MyThread extends Thread {
        public MyThread() {
            super("thread lock");
        }

        @Override
        public void run() {
            synchronized (myThread) {
                System.out.println("4");
            }

        }

    }

the code print is :
1
2
4
3

Through debug, I found that after the run method of thread lock The wait state of thread main is broken.

public static void main(String[] args) {
        myThread.start();
        synchronized (myThread) {
            System.out.println("1");
//            myThread.start();
            System.out.println("2");
 .....
 .....

If the thread starts myThread.start() before synchronized and the thread lock is finished with a breakpoint, myThread.wait() will wait forever, I suspect that at the end of run(), the call to `notifyAll() is hidden.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
tomtom
  • 19
  • 2

0 Answers0