嗨,我正在學習和玩java中的線程。我在一本書中看到Thread對象和Running Thread不是同一件事。即使線程完成它的運行方法,運行線程也會進入死亡狀態,我甚至用isAlive()方法檢查它。我想知道,如果兩者都不同,那麼下面的代碼不能按照我的理解工作。Java線程對象vs正在運行線程
public class Main {
public static void main(String[] args) throws ParseException {
Student s = new Student();
Thread t = new Thread(s);
t.start();
t.run();
t.run();
t.run();
t.run();
t.run();
}
}
class Student implements Runnable {
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
它只顯示這個輸出。 主要 線程0 主要 或本 線程0 主要
從這個結果我明白線程之後完成它的運行方式。正在運行的線程進入死態,並調用Thread obj方法不工作,但我無法理解背後的原因,因爲Thread對象是技能參考,Thread類的其他方法又如何。 like yield()? start()?
這裏是另一種情形了清晰的認識我的話
public class Main {
public static void main(String[] args) throws ParseException {
Student s = new Student();
Thread t = new Thread(s);
t.start();
if (!t.isAlive()) {
t.start();
}
}
}
class Student implements Runnable {
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
文件說,如果我們調用start方法對線程t對象,然後它會拋出java.lang.IllegalThreadStateException。但上面的代碼工作正常。 我很困惑Thread類的哪些方法依賴於運行線程和線程對象。我希望你能理解這個問題。 在此先感謝?
我知道大部分時間它不會發生,但爲什麼運行和其他方法仍然不起作用我的第一個代碼 –
,因爲't'已經在第一次調用't'時使用了'Runnable s' 。開始()'。 –
「如果此線程是使用單獨的Runnable運行對象構造的,那麼將調用該Runnable對象的運行方法; *否則,此方法不執行任何操作並返回。*」--https://docs.oracle.com/javase/7 /docs/api/java/lang/Thread.html#run%28%29 –