The function of the join method is to make the thread that executes asynchronously into synchronous execution. That is, when the start method of the thread instance is called , the method returns immediately, and if you need to use a value computed by this thread after the Start method is called, you must use the Join method. If you do not use the Join method, you cannot guarantee that the thread will execute when it executes to a statement that follows the Start method. After using the Join method, the program will not execute until the thread exits. The following code demonstrates the use of join.
PackageMythread
PublicClassJointhreadExtendsThread
{
Public StaticIntN=0;
StaticSynchronizedvoidInc ()
{
N++;
}
PublicvoidRun ()
{
For(IntI=0; I<10; I++)
Try
{
Inc ();
Sleep3);//3 milliseconds delay in order to make the running result more random
}
Catch(Exception e)
{
}
}
PublicStaticvoidMain (string[] args)ThrowsException
{
Thread threads[]=Newthread[100];
For(IntI=0; I<Threads.length; I++)//Build 100 threads
Threads[i]=NewJointhread ();
For(IntI= 0; I<Threads.length; I++)//Run the 100 threads you just created
Threads[i].start ();
If(Args.length>0)
For(IntI= 0; i < threads.length; i++) // 100 threads continue
threads[i].join ();
system.out.println ( "n= " +&NBSP;JOINTHREAD.N);
}
} /span>
In the routine 2-8 , the number of threads is established, and each thread increases the static variable n by ten. If you output n after each of these threads executes, the n value should be.
1. test 1
Use the following command to run the above program:
Java mythread. Jointhread
The running results of the program are as follows:
n=442
The results of this operation may differ in different operating environments, but General n is not equal to. From the above results, it is certain that all of these threads will output n when they are not executed .
2. Test 2
Use the following command to run the above code:
In the command line above there is a parameter join, in fact, you can use any parameter in the command line, as long as there is a parameter, you can use the join, just to indicate that you want to use the Join method to synchronize the three threads.
The running results of the program are as follows:
n=
no matter what kind of running environment you run the above command, you will get the same result: n=1000. This is a good indication that each of these threads must have been executed, so n must be equal to.
The join method of the multi-thread join method is not used much, and when a thread executes to the join () method of the B thread, a waits for the B thread to run, and the A thread executes. When you use the Join () method, an exception is generated.
Use a small program to illustrate the skill of the Join method:
Class Demo implements Runnable
{
public void Run ()
{
for (int x=1;x<100; x + +)
{
System.out.println (Thread.CurrentThread (). GetName () + "..." + x);
}
}
}
public class Joindemo
{
public static void Main (string[] args) throwsexception
{
Demo d = new demo ();
Thread T1 = newthread (d);
Thread t2 = newthread (d);
T1.start ();
T1.join ();
T2.start ();
for (int x=1;x<100; x + +)
{
System.out.println (Thread.CurrentThread (). GetName () + "..." + x);
}
}
}
The main thread down, hit the T1.join (), T1 to apply to join the operation, that is, the CPU execution right. At this time the CPU execution right in the main thread hand, the main thread will be the CPU executive right to release, into a frozen state. Alive only T1, only when the T1 take the executive right to print out the data, the main thread is back to run .
The Join method can be used to temporarily join a thread , a thread in the process, if satisfied with the condition, we can temporarily join a thread, so that the thread is finished, another thread to continue to run.
What if the T1.join () and T2.start () positions are exchanged ? The main thread opens the T1, T2, this time the CPU execution power is still in the main thread hand. When the main thread touches the T1.join (), the release execution is in a frozen state. the Living T1, T2 all have the execution qualification, this time CPU then executes to T1 and T2 alternately . The main thread to wait until the end of T1 to live, as for the T2 knot does not end, and the main thread does not have the slightest relationship. if T1 ends, T2 is not over, the main thread will execute with T2 execution . The main thread who joins, it waits for WHO. In other words, Whoever lets it put the executive right out, it waits for someone to die. As for WHO to rob, it doesn't matter .
Java Basic Tutorial Join method detailed Java Multithreading tutorial
The topics covered in this chapter include:
1. Join () Introduction
2. Join () source analysis (based on jdk1.7.0_40)
3. Join () example
1. Join () Introduction
Join () is defined in Thread.java.
Join (): Lets the main thread wait for the "child threads" to end before they can continue to run. This sentence may be a bit obscure, we still use examples to understand:
Copy CodeThe code is as follows:
Main thread
public class Father extends Thread {
public void Run () {
Son s = new Son ();
S.start ();
S.join ();
...
}
}
Child threads
public class Son extends Thread {
public void Run () {
...
}
}
Description
There are two classes father (the main thread class) and son (child threading Class). Because son is created and started in father, Father is the main thread class and son is the child thread class.
In the father main thread, create a new child thread s through New Son (). The "Child thread S" is then started through S.start (), and S.join () is called. After calling S.join (), the Father main thread waits until the "child thread S" is finished, and after the "Child thread S" has finished running, the father main thread can then run. This is what we call the "join" function, which is to allow the main thread to wait for the child thread to end before it can continue to run!
2. Join () source analysis (based on jdk1.7.0_40)
Copy CodeThe code is as follows:
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");
}
if (Millis = = 0) {
while (isAlive ()) {
& nbsp; Wait (0);
}
} else {
while (isAlive ()) {
long delay = Millis-now;
if (delay <= 0) {
break;
}
Wait (delay);
now = System.currenttimemillis ()-base;
}
}
}
Description
From the code, we can see. When millis==0, it enters the while (IsAlive ()) loop, i.e. the main thread waits as long as the child thread is alive.
We understand the use of join () based on the code above explaining the function of join ()!
Problem:
Although S.join () is called in the "Father Main Thread", S.join () is the join () called by "Child thread S". Then, IsAlive () in the Join () method should be judged as "child thread S" is not alive state; the corresponding wait (0) should also be "let child thread S" wait. But if this is the case, how can s.join () be "Let the main thread wait until the child thread S is finished", should be let "the child thread waits for the right (because call the child thread object s's Wait method)"?
Answer: The role of Wait () is to have the "current thread" wait, and here the "current thread" refers to the thread that is currently running on the CPU. So, although it is called the Wait () method of the child thread, it is called through the "main thread", so the main thread is dormant, not "child thread"!
3. Join () example
After understanding the role of join (), follow the example to see the use of join ().
Copy CodeThe code is as follows:
Source Code of Jointest.java
public class jointest{
public static void Main (string[] args) {
try {
Threada T1 = new Threada ("T1"); New "Thread T1"
T1.start (); Start "Thread T1"
T1.join (); Add "Thread T1" to the main thread main, and "main thread main () will wait for it to complete"
System.out.printf ("%s finish\n", Thread.CurrentThread (). GetName ());
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
Static class Threada extends thread{
Public Threada (String name) {
Super (name);
}
public void Run () {
System.out.printf ("%s start\n", This.getname ());
Delay operation
for (int i=0; I <1000000; i++)
;
System.out.printf ("%s finish\n", This.getname ());
}
}
}
Operation Result:
Copy CodeThe code is as follows:
T1 start
T1 finish
Main finish
Result Description:
Run the process
(01) Create a new thread T1 through new Threada ("T1") in main thread main. Next, start thread T1 with T1.start () and execute T1.join ().
(02) after executing t1.join (), "main thread main" will enter "blocking state" to wait for T1 to finish running. After the "Child thread T1" ends, it wakes up "main thread main", "Main thread" regain CPU execution and continue running.
Multi-Thread Join method