An instance of the join method of Thread in Java

  • 2020-04-01 03:32:29
  • OfStack

This article illustrates the join method of Java Thread as an example. Share with you for your reference. The specific implementation method is as follows:

The join
Public final void the join ()
Throws InterruptedException waits for the thread to terminate.

Throws:
InterruptedException - if any thread interrupts the current thread. When the exception is thrown, the interrupted state of the current thread is cleared.
 
In the following example, after A calls the join method, the process will not be allocated until the thread of A is no longer running

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, and the main function allocates the Thread to A. When A finishes running, the Thread will be released. To other objects. < br / >         B.start();
        for (int i = 1;i < 20;i++)
        {
            System.out.println(" Apples fall from trees "+ i);
        }
        System.out.println(" Apple didn't ");
    }
} class ThreadTest5 implements Runnable
{
    public void run()
    {
        for (int i = 1;i < 10;i++)
        {
            System.out.println(Thread.currentThread().getName()+" Eat an apple "+(i));
        }
    }
}

The running result is:

Thread-0 eats apple 1
Thread-0 eats apple 2
Thread-0 eats apple 3
Thread-0 eats apple 4
Thread-0 eats apple 5
Thread-0 eats apple 6
Thread-0 eats apple 7
Thread-0 eats apple 8
Thread-0 eats apple 9
Apples fall on the tree
Apples fall on the tree
Apples fall from trees
Apples fall from trees
Apples fall from trees
Apples fall on the tree
Thread-1 eats apple 1
Apples fall on the tree
Thread-1 eats apple 2
Apples fall on the tree
Thread-1 eats apple 3
Apples fall on trees
Thread-1 eats apple 4
Apples fall on the tree
Thread-1 eats the apple 5
Apples fall on the tree
Thread-1 eats apple - 6
Thread-1 eats apple 7
Thread-1 eats apple - 8
Thread-1 eats apple - 9
Apples fall on the tree
Apples fall on the tree
Apples fall from trees
Apples fall from trees
Apples fall on the tree
Apples fall from trees
Apples fall on the tree
Apples fall from trees
Apple didn't

Thread-0 value is the Thread where A is. When the Thread where A is running is finished, the subsequent Thread will be contended by the main function and the B process.

I hope this article has been helpful to your Java programming.


Related articles: