Usage of Thread Join ()

Source: Internet
Author: User

The Java thread class has a join () method, which has not been known for a long time until you see this article. http://auguslee.iteye.com/blog/1292203

In Java thread, the Join () method is primarily to let the thread that invokes the method complete the contents of the Run method and then execute the code after the join () method. Example:

Threadtesterb in the Threadtestera.join () is blocked after it is called and continues until Threadtestera execution is complete.

[Java]View Plaincopy
  1. Class Threadtestera implements Runnable {
  2. private int counter;
  3. @Override
  4. public Void Run () {
  5. While (counter <= ) {
  6. System.out.print ("Counter =" + Counter + ");
  7. counter++;
  8. }
  9. System.out.println ();
  10. }
  11. }
  12. Class Threadtesterb implements Runnable {
  13. private int i;
  14. @Override
  15. public Void Run () {
  16. While (i <= ) {
  17. System.out.print ("i =" + i + "");
  18. i++;
  19. }
  20. System.out.println ();
  21. }
  22. }
  23. Public class Threadtester {
  24. public static void Main (string[] args) throws interruptedexception {
  25. Thread T1 = new Thread (new Threadtestera ());
  26. Thread t2 = new Thread (new Threadtesterb ());
  27. T1.start ();
  28. T1.join (); //wait T1 to be finished
  29. T2.start ();
  30. T2.join (); //In the This program, this is May removed
  31. }
  32. }


After the T1 is started, the join () method is called until the T1 count task ends and the T2 starts, and then T2 also starts counting the tasks. As you can see, in the instance, two threads are executed in strict order.

If the execution of T2 depends on the complete data in T1, this method can ensure the synchronization of the two threads well.

Usage of Thread Join ()

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.