在下面的代碼片段中,“母馬不吃燕麥”。沒有被列印出來。預計在完成 2000 毫秒的睡眠后,它將運行該列印陳述句,但它永遠不會到達那里。
public class BadThreads {
static String message;
private static class CorrectorThread
extends Thread {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {}
// Key statement 1:
message = "Mares do eat oats.";
}
}
public static void main(String args[])
throws InterruptedException {
(new CorrectorThread()).start();
message = **"Mares do not eat oats.**";
Thread.sleep(2000);
// Key statement 2:
System.out.println(message);
}
}
uj5u.com熱心網友回復:
正在達到您標記的陳述句。
當您的主執行緒休眠時,“CorrectorThread”將訊息的值更改為“Mares do eat oats”。并且不列印訊息。CorrectorThread 然后完成了執行。
主執行緒從睡眠中醒來并列印變數 message 的值,現在是“Mares do eat oats”。
請注意,變數訊息由兩個執行緒共享。也許你已經習慣了 C 的 fork() 陳述句,它會啟動一個新行程,隨后不再與主執行緒共享記憶體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491158.html
