An interesting problem encountered in Java multithreading Learning
Today, I casually wrote a program for mutual thread scheduling. The Code is as follows:
class First extends Thread{public First(){start();}synchronized public void run(){try{wait();}catch(InterruptedException e){e.printStackTrace();}try{sleep(2000);}catch(InterruptedException e){e.printStackTrace();}System.out.println("hello world~");}}class Second extends Thread{First first;public Second(First first){this.first = first;start();}synchronized public void run(){try{wait();}catch (InterruptedException e1){e1.printStackTrace();}synchronized( first ){try{sleep(2000);System.out.println("I'm faster than first~");}catch(InterruptedException e){e.printStackTrace();}first.notifyAll();}}}public class Main{public static void main(String[] args) throws InterruptedException{First first = new First();Second second = new Second(first);synchronized( second ){System.out.println("I'm faster than second~");second.notifyAll();}}}
I thought the output would be smooth, but the problem was that only one line was output: I'm faster than second ~
The program has been in a non-responsive state. After a long struggle, I finally want to understand the same thing: in the main function, for second. the call of policyall () is earlier than the wait () call in second (because it is multi-thread parallel, the function response time is irrelevant to the code order). In this way, second is awakened first, the second step begins wait, so it is in the unresponsive state.
Improvement Method: in second. before calling yyall (), you can leave a little time to let second's wait call start. In fact, this time is so short that you only need to add a line of output statement on my computer. For the sake of insurance, we added a sleep. The improved code is as follows:
class First extends Thread{public First(){start();}synchronized public void run(){try{wait();}catch(InterruptedException e){e.printStackTrace();}try{sleep(2000);}catch(InterruptedException e){e.printStackTrace();}System.out.println("hello world~");}}class Second extends Thread{First first;public Second(First first){this.first = first;start();}synchronized public void run(){try{wait();}catch (InterruptedException e1){e1.printStackTrace();}synchronized( first ){try{sleep(2000);System.out.println("I'm faster than first~");}catch(InterruptedException e){e.printStackTrace();}first.notifyAll();}}}public class Main{public static void main(String[] args) throws InterruptedException{First first = new First();Second second = new Second(first);System.out.println("wating for all threads prepared~");Thread.sleep(2000);synchronized( second ){System.out.println("I'm faster than second~");second.notifyAll();}}}Output result:
Wating for all threads prepared ~
I'm faster than second ~
I'm faster than first ~
Hello world ~