Java Concurrency Programming Example (vi): Waiting for thread execution to terminate _java

Source: Internet
Author: User
Tags thread class

In some scenarios, we have to wait for the thread to finish before we can do the next step. For example, some programs need to initialize some resources before they start executing. At this point, we can start a thread dedicated to the initialization task, wait until the thread task completes, then to execute the other parts.

For this reason, the thread class provides us with the join () method. When we use the thread object to call this method, the thread object that is dropping the call is deferred until execution of the called object is completed before execution begins.

In this section, the sample program demonstrates waiting for the initialization method to complete before performing another task.

Know it

Follow the steps shown below to complete the sample program.

1. Create a class named Datasourcesloader and implement the Runnable interface. The code is as follows:

Copy Code code as follows:

public class Datasourcesloader implements Runnable {

2. Implement the Run () method, print a piece of information to the console to explain the start, then sleep for 4 seconds, and then print a message to the console to explain the end of the thread execution. The code is as follows:

Copy Code code as follows:

@Override
public void Run () {
SYSTEM.OUT.PRINTF ("Beginning Data sources loading:%s\n",
New Date ());
try {
TimeUnit.SECONDS.sleep (4);
catch (Interruptedexception e) {
E.printstacktrace ();
}

System.out.printf ("Data sources loading has finished:%s\n",
New Date ());
}


3. Create a class named Networkconnectionsloader and implement the Runnable interface. Implement the Run () method with the same method code as the Datasourcesloader class's Run () method, which is only 6 seconds of sleep.

4. Implement the main class of the sample and implement the main () method. The code is as follows:

Copy Code code as follows:

public class Main {
public static void Main (string[] args) {

5. Create a Datasourcesloader object and a thread object that initiates its execution. The code is as follows:
Copy Code code as follows:

Datasourcesloader Dsloader = new Datasourcesloader ();
Thread thread1 = new Thread (Dsloader, "Datasourcesloader");

6. Create a Networkconnectionsloader object and a thread object that initiates its execution. The code is as follows:
Copy Code code as follows:

Networkconnectionsloader Ncloader = new Networkconnectionsloader ();
Thread thread2 = new Thread (Ncloader, "Networkconnectionsloader");

7. Call the Start () method of the two thread objects. The code is as follows:
Copy Code code as follows:

Thread1.start ();
Thread2.start ();

8. Call the Join () method to wait for two threads to complete their task. This method throws a Interruptedexception exception, so you want to catch the exception. The code is as follows:
Copy Code code as follows:

try {
Thread1.join ();
Thread2.join ();
catch (Interruptedexception e) {
E.printstacktrace ();
}

9. Print a Word to the console indicating that the execution of the program is complete. The code is as follows:
Copy Code code as follows:

System.out.printf ("Main:configuration has been loaded:%s\n",
New Date ());

10. Run the program to see the execution effect.

Know the reason why

When we run this sample program, we can see two threads starting their execution. First, the datasourcesloader completes its execution, and then the networkconnectionsloader completes its execution. At this point, the main thread continues its execution, and then prints out the termination information to the console.

Endless

Java provides two additional overloaded join () methods:

Copy Code code as follows:

Join (long milliseconds)
Join (long milliseconds, long Nanos)

The first way is not until the call completes the task, but waits for the time specified by the parameter to begin execution; For example, if Thread1 calls the method, Thread1.join (1000), the condition that the thread1 thread satisfies one of the following conditions will continue to execute:

1.thread2 to complete its execution;
After 2.1000 milliseconds;

When one of these two conditions is true, the join () method returns, starting to continue with the original task.

The second method is similar to the first, except for a nanosecond-time parameter.

Copycat

This article is from the "Java 7 Concurrency Cookbook" (D-Gua to "Java7 concurrent Sample Set") translation, only as learning materials used. No authorization shall be applied to any commercial act.

Small has become

The full version of the sample code used in this section.

Complete code for the Datasourcesloader class

Copy Code code as follows:

Package com.diguage.books.concurrencycookbook.chapter1.recipe6;

Import Java.util.Date;
Import Java.util.concurrent.TimeUnit;

/**
 * date:2013-09-19
 * time:09:15
 */
public class Datasourcesloader implements Run nable {
    @Override
    public void Run () {
     & nbsp;  System.out.printf ("Beginning Data sources loading:%s\n",
                 new Date ());
        try {
             TimeUnit.SECONDS.sleep (4);
       } catch (Interruptedexception e) {
             E.printstacktrace ();
       }

System.out.printf ("Data sources loading has finished:%s\n",
New Date ());
}
}

Complete code for the Networkconnectionsloader class

Copy Code code as follows:

Package com.diguage.books.concurrencycookbook.chapter1.recipe6;

Import Java.util.Date;
Import Java.util.concurrent.TimeUnit;

/**
 * date:2013-09-19
 * time:09:21
 */
public class Networkconnectionsloader Implem Ents Runnable {
    @Override
    public void Run () {
         System.out.printf ("Beginning Data sources loading:%s\n",
                 new Date ());
        try {
             TimeUnit.SECONDS.sleep (6);
       } catch (Interruptedexception e) {
             E.printstacktrace ();
       }

System.out.printf ("Data sources loading has finished:%s\n",
New Date ());
}
}

The complete code for the main class

Copy Code code as follows:

Package com.diguage.books.concurrencycookbook.chapter1.recipe6;

Import Java.util.Date;

/**
* date:2013-09-19
* TIME:09:25
*/
public class Main {
public static void Main (string[] args) {
Datasourcesloader Dsloader = new Datasourcesloader ();
Thread thread1 = new Thread (Dsloader, "Datasourcesloader");

Networkconnectionsloader Ncloader = new Networkconnectionsloader ();
Thread thread2 = new Thread (Ncloader, "Networkconnectionsloader");

Thread1.start ();
Thread2.start ();

try {
Thread1.join ();
Thread2.join ();
catch (Interruptedexception e) {
E.printstacktrace ();
}

System.out.printf ("Main:configuration has been loaded:%s\n",
New Date ());
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.