This article describes the join method of Thread in Java. Share it with everyone for your reference. The specific implementation method is as follows:
join
public final void join()
throws InterruptedException and waits for the thread to terminate.
Throws:
InterruptedException - if any thread interrupts the current thread. When this exception is thrown, the interrupt status of the current thread is cleared.
In layman's terms, the following example means that after A calls the join method, the process will be allocated only after the thread in which A is located is no longer running.
Copy the code as follows: public class joinThread {
public static void main(String [] args) throws Exception{
ThreadTest5 t = new ThreadTest5();
Thread A = new Thread(t);
Thread B = new Thread(t);
A.start();
A.join(); //Here A calls the join method of Thread. The main function allocates the thread to A. When A finishes running, the thread will be released. to other objects.
B.start();
for (int i = 1;i < 20;i++)
{
System.out.println("Apples fell from the tree" + i);
}
System.out.println("Apple is gone");
}
}
class ThreadTest5 implements Runnable
{
public void run()
{
for (int i = 1;i < 10;i++)
{
System.out.println(Thread.currentThread().getName()+"Eat Apple"+(i));
}
}
}
The running result is:
Thread-0 eat apple 1
Thread-0 eat apple 2
Thread-0 eat apple 3
Thread-0 eat apple 4
Thread-0 eat apple 5
Thread-0 eat apple 6
Thread-0 eat apple 7
Thread-0 eat apple 8
Thread-0 eat apple 9
Apple falling from the tree 1
Apples falling from the tree 2
Apples falling from the tree 3
Apples falling from the tree 4
Apple 5 falls from the tree
Apple 6 fell from the tree
Thread-1 eat apple 1
Apple 7 fell from the tree
Thread-1 eats apple 2
Apple 8 falls from the tree
Thread-1 eat apple 3
Apples falling from the tree 9
Thread-1 eat apple 4
Apple 10 falls from the tree
Thread-1 Eat Apple 5
Apples falling from the tree 11
Thread-1 eats apple 6
Thread-1 Eat Apple 7
Thread-1 eat apple 8
Thread-1 eat apple 9
Apples falling from the tree 12
Apples falling from the tree 13
Apples falling from the tree 14
Apple 15 fell from the tree
Apple falling from the tree 16
Apples falling from the tree 17
Apples falling from the tree 18
Apples falling from the tree 19
Apple is gone
Thread-0 is the thread where A is located. When the thread where A is located finishes running, subsequent threads will be competed by the main function and process B.
I hope this article will be helpful to everyone’s Java programming.