我剛剛在我的下面的代碼中的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