编程语言
首页 > 编程语言> > 这个线程可以活着吗以及如何使用java.lang.Thread.join()方法

这个线程可以活着吗以及如何使用java.lang.Thread.join()方法

作者:互联网

我以前读过一些SO问题和文档,但没有找到我的答复:

> How long a thread will be alive in java?
> When is a Java thread alive?
> http://journals.ecs.soton.ac.uk/java/tutorial/java/threads/states.html

所以…

public class MyThread extends Thread {
  public MyThread() {
    this.setName("MyThread-" + System.currentTimeMillis());
    this.start();
  }

  public MyThread(long millis) throws InterruptedException {
    this.setName("MyThread-" + System.currentTimeMillis());
    this.join(millis);
    this.start();
  }

  @Override
  public void run() {
    System.out.println("I am running...");
    // This thread does not sleep... no Thread.sleep() in run method.
    // Do some things like requesting a database
    // Database response happens in less time that the timeout
  }
}

public class MyClass {

  public MyClass(){
    for (int i = 0; i < 5; i++) {
      Thread t1 = new MyThread();
      t1.join(5000);
      if (t1.isAlive()) {
        System.out.println("I'm alive");
        // do some things
      } else {
        System.out.println("I'm not alive");
      }

      Thread t2 = new MyThread(5000);
      if (t2.isAlive()) {
        System.out.println("I'm alive");
        // do some things
      } else {
        System.out.println("I'm not alive");
      }

    }
  }
}

似乎不可能但是其中一个可以活着吗? t2怎么样?
在start()之后调用join()时发生的事情

有关信息,我正在使用:

> JVM:Java HotSpot(TM)客户端VM(20.45-b01,混合模式,共享)
> Java:版本1.6.0_45,供应商Sun Microsystems Inc.

阅读部分回复后更新

如果我理解,更好的实现将是这样的:

public class MyThread extends Thread {
  public MyThread() {
    super("MyThread-" + System.currentTimeMillis());
  }

  @Override
  public void run() {
    System.out.println("I am running...");
    // This thread does not sleep... no Thread.sleep() in run method.
    // Do some things like requesting a database
    // Database response happens in less time that the timeout
  }
}

public class MyClass {

  public MyClass(){
    for (int i = 0; i < 5; i++) {
      Thread t1 = new MyThread();
      t1.start();
      t1.join(5000);

      if (t1.isAlive()) {
        System.out.println("I'm alive");
        // do some things
      } else {
        System.out.println("I'm not alive");
      }
    }
  }
}

这两个回复对我帮助很大:https://stackoverflow.com/a/29775219/1312547https://stackoverflow.com/a/29775083/1312547

解决方法:

请注意,尽管Thread.join(long)的(JDK 7)文档说明了

Waits at most millis milliseconds for this thread to die.

它还继续

This implementation uses a loop of this.wait calls conditioned on this.isAlive.

而Thread.isAlive说:

A thread is alive if it has been started and has not yet died.

所以用你的代码:

>调用t1.isAlive()时,由于您在启动线程后(从构造函数)加入,因此它始终为false.
>当调用t2.isAlive()时,大部分时间都是真的

>你在开始线程之前加入了(在构造函数中),它立即返回
>线程刚刚启动(在构造函数中)

所以回答你的问题

It seems it can not be but could one of the t1 be alive ?

对于t1,不,只要你等待的时间超过它运行的时间.对于t2,是的.

标签:java,multithreading,jdk1-6
来源: https://codeday.me/bug/20190609/1205144.html