Blog.csdn.net/chenkaibsw/…

1. An overview of the

  • The main function of the JOIN method is synchronization. It can change parallel execution between threads into serial execution

Example 2.

  • thread.join();
  • thread.join(long millis); // Wait for the millis time for the serial to continue in parallel.
Public class JoinThreadTest {public void a(Thread joinThread) {system.out.println (" method a executes... ); joinThread.start(); try { joinThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } system.out. println("a method is executed...") ); } public void b() {system.out.println ("....") ); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } system.out. println(" thread executed...") ); } /** Method A executes... The threading starts executing.... The threading is complete... A Method is executed...... */ public static void main(String[] args) { JoinThreadTest joinThreadTest = new JoinThreadTest(); JoinThread = new Thread(new Runnable() {@override public void run() {joinThreadtest.b (); }}); New Thread(new Runnable() {@override public void run() {joinThreadTest. } }).start(); }}Copy the code

3. The source code

public class Thread implements Runnable { public final void join() throws InterruptedException { join(0); } public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis();  long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } // Hibernate indefinitely if (millis == 0) {//isAlive is a blocked thread, While (isAlive()) {while (isAlive()) {while (isAlive()) {while (isAlive()) {while (isAlive()) {while (isAlive()) { } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } } //Tests if this thread is alive. A thread is alive if it has been started and has not yet died. Public final native Boolean isAlive(); public final native Boolean isAlive(); } Thread's join method has the modification of synchronized, and synchronized obtains the object lock as an instance of the Thread. When the Thread terminates, the notifyAll() method of the Thread itself is called to notifyAll threads waiting on the Thread object.Copy the code

That is, if the plug thread is alive, wait() for the current thread. When the plug thread completes, notifyAll () is called, and notify continues. Synchronized is special when the object lock is an instance of a thread. When the thread terminates, the notifyAll() method of the thread itself is called, notifying all threads waiting on the thread object.

4. To summarize

  • The join method must be placed after start. If it is placed before start, it does not perform synchronization

See article: Join method in Java for details