Java线程join()混淆

时间:2018-02-06 13:22:58

标签: java multithreading

我试图按照这个例子来理解join()方法:

class PrintDemo {

   public void printCount() {

      try {

         for(int i = 5; i > 0; i--) {
            System.out.println("Counter   ---   "  + i );
         }
      } catch (Exception e) {
         System.out.println("Thread  interrupted.");
      }
   }
}

class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;
   PrintDemo  PD;

   ThreadDemo(String name,  PrintDemo pd) {
      threadName = name;
      PD = pd;
   }

   public void run() {

      synchronized(PD) {
         PD.printCount();
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }

   public void start () {
      System.out.println("Starting " +  threadName );

      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThread {

   public static void main(String args[]) {
      PrintDemo PD = new PrintDemo();

      ThreadDemo T1 = new ThreadDemo("Thread - 1 ", PD);
      ThreadDemo T2 = new ThreadDemo("Thread - 2 ", PD);

      T1.start();
      T2.start();

      // wait for threads to end
      try {
         T1.join();
         T2.join();
      } catch (Exception e) {
         System.out.println("Interrupted");
      }
   }
}

我知道T1.join()例如使主线程等待T1完成以继续其流程。我在这里纠正吗?

所以,我修改了这样的代码:

      System.out.println("1");
      T1.start();
      System.out.println("2");
      T2.start();

      // wait for threads to end
      try {
         System.out.println("3");
         T1.join();
         System.out.println("4");
         T2.join();
         System.out.println("5");
      } catch (Exception e) {
         System.out.println("Interrupted");
      }

为了尝试并遵循完整的流程。

这就是我每次都得到的:

1
Starting Thread - 1 
2
Starting Thread - 2 
3
4
5
Counter   ---   5
Counter   ---   4
Counter   ---   3
Counter   ---   2
Counter   ---   1
Thread Thread - 1  exiting.
Counter   ---   5
Counter   ---   4
Counter   ---   3
Counter   ---   2
Counter   ---   1
Thread Thread - 2  exiting.

我无法解释......

为什么计数器打印在“5”字符后打印? 我可能不太了解加入问题...

3 个答案:

答案 0 :(得分:6)

启动一个线程(A),启动另一个线程(B)。

你等待线程A完成 - 这几乎是立竿见影的,因为它除了启动线程B之外几乎没有做任何事情 - 但是线程B仍然是独立运行的。

答案 1 :(得分:2)

正如@Micheal所说,你的主线不是加入"欲望"线程,也许这段代码可以帮助你澄清。它可以帮助主线程与内部线程连接。

Java interpreter architecture: win32.

答案 2 :(得分:1)

  

我正在尝试...了解join()方法

result = result.append(df1b) 很容易理解。它所做的就是等待线程Dim objWinHttp As Variant Set objWinHttp = CreateObject("WinHttp.WinHttpRequest.5.1") Dim url As String url = "https://destination.com/api/v1/destination1 objWinHttp.Open "post", url, False objWinHttp.setRequestHeader "Content-type", "application/json" objWinHttp.setRequestHeader "Content-Length", Len(json) objWinHttp.send json Dim result As String result = = objWinHttp.responseText 死掉。它没有做任何其他事情。最特别的是,它对线程t.join()没有任何作用。

t的调用无效,如果t已经完成,则立即返回。否则它将什么都不做,并且在t.join() 完成之前它不会返回。