Thread threads Join method Self-understanding
Thread.Join (): Waits for thread thread to run to terminate, which means that main-thread (main thread) must wait for the thread thread to run to the end before it can continue thread.join (); The following code
Thread.Join (long time): Threads thread Thread waits for the duration, Main-thread can execute, note that after time, thread threads are not finished, Main-thread can also run
Note: The above 2 methods must be alive when the thread, only this effect, otherwise there will not be.
The join () method source code is a method that calls the wait () method, the Wait method is object, and the thread wait is the object lock is freed, so calling the join () method is the thread that frees the object lock to block the same wait () method.
classRunner1Implementsrunnable{@Override Public voidrun () {Try{System.out.println (Thread.CurrentThread (). GetName ()+ "Begin ..."); Thread.Sleep (2000); //① } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Finish ..."); }}classRunner2Implementsrunnable{@Override Public voidrun () {Try{System.out.println (Thread.CurrentThread (). GetName ()+ "Begin ..."); Thread.Sleep (1000); //② } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Finish ..."); }} Public classTest_thread_join {/*** Thread.Join () waits for the thread to end, then executes the code after Thread.Join * Thread.Join (n) waits for the thread to end or n time, after executing the code behind Thread.Join*/ Public Static voidMain (string[] args) {Runner1 R1=NewRunner1 (); Runner2 R2=NewRunner2 (); Thread T1=NewThread (R1, "Thread-a"); Thread T2=NewThread (R2, "Thread-b"); T1.start ();//T1 is alive.T2.start (); Try{t1.join ();//when executing this code, the main thread is blocked, T2. This thread may be running, or it may endT2.join ();//If the T2 thread is already running at the end of the T1.join () execution, the line of code is ineffective ③ }Catch(interruptedexception e) {e.printstacktrace (); } run (); } Public Static voidrun () { for(inti = 0; I < 5; i++) {System.out.println ("Main I:" +i); } }}
Effect:① thread-a sleep 2 seconds,②thread-b sleep 1 seconds
Execution Result:
Conclusion: T1.join (); When executing, the main method blocks waiting for the T1 thread to execute, and after the T1 thread executes, the program executes T2.join (), at which point the T2 thread is dead and the run ends, and this line of code has no effect. If the T2 is not dead, then Main-thread must wait for thread-b to die before executing the code later. If ③ This line of code is commented, and t1.join () T2 thread is still alive after execution, then Main-thread and Thread-b threads will compete for CPU resources, and they may run interactively.
Thread threads Join method Self-understanding