简体   繁体   中英

Unexpected behavior of the following Java program

In following java program Thread.sleep(1000) is called after for loop. However, it is getting Interrupted before printing all value. Inside the run method, it should print all value then go for sleep, Why I am getting unexpected behavior of the following Java program.

Output:

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

Interrupted Program

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()

Prints this throwable and its backtrace to the standard error stream.

You print values to the standard output stream , so you basically have two streams involved. Since they flush at different times, the order of messages is truly unpredictable.

Run the snippet several times, and you may get lucky and see the order you were expecting :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM