![](/img/trans.png)
[英]Thread.join() and Thread.interrupt() doesn't stop the thread
[英]java Thread.join doesn't work as expected
我有以下課程
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name) {
threadName = name;
}
public void run() {
for(int i = 5; i > 0; i--) {
System.out.println("Thread " + threadName + " Counter --- " + i );
}
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("Sleep issue");
}
System.out.println("Finishing run");
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("Sleep issue");
}
}
public void start () {
t = new Thread (this, threadName);
t.start ();
}
}
如下測試
public class Main {
public static void main(String[] args) {
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ");
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ");
T1.start();
T2.start();
//Let's give some time for threads to run
try {
Thread.sleep(10);
} catch (Exception e) {
System.out.println("Main sleep issue");
}
try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
System.out.println("Finishing main.");
}
}
為什么盡管我使用T1.join()和T2.join()等待它們完成,但為什么我總是在輸出“ Finishing run”之前得到“ Finishing main”? 最初,我認為這可能是由於緩沖區延遲所致,所以我在run()的末尾添加了Thread.sleep(1000)以便花一些時間來打印“ Finishing run”,但這沒有幫助。 我猜這是由於Thread.sleep(1000)的首次出現(當我刪除它時,它的工作正常),但不知道為什么。
因為這個:
public void start () {
t = new Thread (this, threadName);
t.start ();
}
因此,您的ThreadDemo
實例永遠不會真正作為線程啟動:打印Finishing run
消息的線程就是在該方法中創建的線程。 該線程與ThreadDemo
之間沒有鏈接。
刪除start()
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.