[英]Unexpected behavior of the following Java program
在下面的 java 程序Thread.sleep(1000)
在 for 循環之后被調用。 但是,在打印所有值之前它會被中斷。 在 run 方法中,它應該打印所有值然后進入睡眠狀態,為什么我會遇到以下 Java 程序的意外行為。
輸出:
java.lang.InterruptedException: sleep interrupted
Value=0
at java.lang.Thread.sleep(Native Method)
Value=1
at com.thread.TestThread.run(InterruptThread.java:21)
Value=2
Value=3
Value=4
Value=5
Value=6
Value=7
Value=8
Value=9
中斷的程序
public class InterruptThread {
public static void main(String[] args) {
TestThread thread = new TestThread();
thread.start();
thread.interrupt();
}
}
class TestThread extends Thread{
@Override
public void run() {
try {
for(int i=0; i<10; i++){
System.out.println("Value="+ i);
}
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread is interrupted");
e.printStackTrace();
}
}
}
public void printStackTrace()
將此 throwable 及其回溯打印到標准錯誤流。
您將值打印到標准輸出流,因此您基本上涉及兩個流。 由於它們在不同時間刷新,因此消息的順序確實不可預測。
多次運行該代碼段,您可能會很幸運並看到您期望的順序:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.