[英]Java Thread.sleep not working as expect in runnable implement
我想弄清楚Thread.sleep
是如何工作的,所以我創建了以下代碼:
public static void main() {
Runnable runnable = new Runnable() {
public void run() {
try {
Thread.sleep(1000);
System.out.println("Middle");
} catch (InterruptedException e) {
}
}
};
System.out.println("Before");
Thread t2 = new Thread(runnable);
t2.start();
System.out.println("After");
但是,它只在控制台中打印Before
和After
並跳過Middle
。
所以我想知道這個 Thread.sleep 是否會破壞 Runnable 部分?
使用join()使您的主線程等待您的線程 (t2) 執行完成。
public static void main(String[] args) throws InterruptedException {
Runnable runnable = new Runnable() {
public void run() {
try {
Thread.sleep(1000);
System.out.println("Middle");
} catch (InterruptedException e) {
}
}
};
System.out.println("Before");
Thread t2 = new Thread(runnable);
t2.start();
t2.join();
System.out.println("After");
輸出:之前中間之后
參考這篇文章了解join() : 這個線程加入代碼是什么意思?
參考這篇文章了解主線程: Java中的主線程何時停止?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.