我刚刚在我的下面的代码中的isAlive方法中看到问题,它将返回false,甚至thread.start()方法已被调用,即使我也试图在主线程中添加一些睡眠以及我的线程对象,但它仍然具有相同的行为。线程中错误的IsAlive()行为
public class ThreadBehaviour implements Runnable {
private Thread t;
ThreadBehaviour() {
t = new Thread();
t.setName("hello");
}
public void start() throws InterruptedException {
if (!t.isAlive()) {
t.start();
//Thread.currentThread().sleep(1000L);
//t.sleep(3000l);
System.out.println(t.getName() + " Running....." + t.isAlive());// why is Alive is false here?
}
}
public static void main(String args[]) throws InterruptedException {
ThreadBehaviour myThread = new ThreadBehaviour();
myThread.start();
}
@Override
public void run() {
t.run();
}
}
老实说,我不太清楚你在这里试图做什么 – TheLostMind
我只是想清除有关isAlive方法的概念,我的问题是在我的开始方法,即使我写t.start然后为什么isAlive返回false? –
要测试'isAlive',创建一个独立的类来实现'Runnable',并使用它创建并启动主类中的线程。在你的Runable的'run()'中,使用'sleep'和一个循环。在你的主体中,检查我的线程是否存活 – TheLostMind