Today casually wrote a program between threads scheduling each other, 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 an unresponsive state, tangled for a long time finally want to understand is such a thing: in the main function, the call to Second.notifyall () is earlier than the wait () call in second (because it is multithreaded parallel, so the function response time is independent of the Code sequencing), This wakes up the second first, and then the second only begins to wait, so it is in an unresponsive state.
Improved method: As long as the Second.notifyall () call to leave a little time before the second wait call start, in fact, this time is so short that on my computer only need to add a line before the output statement. To be on the safe side, add a sleep, and 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 (+); 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~
An interesting problem encountered in Java multithreaded learning