简体   繁体   English

为什么不抓住打印?

[英]Why doesn't Catch Print?

try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted, NOT PRINTED");
}
System.out.println ("This statement is printed");

in this code sleep throws an interrupted exception and yet this doesnt print the catch statements in the output.Why? 在这段代码中,sleep会抛出一个中断的异常,但这并不会在输出中打印catch语句。为什么?

You should read the full Javadoc for the sleep method (note the emphasis): 你应该阅读睡眠方法的完整Javadoc (注意重点):

sleep 睡觉

public static void sleep(long millis) throws InterruptedException

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. 导致当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性。 The thread does not lose ownership of any monitors. 该线程不会失去任何监视器的所有权。

Parameters : 参数
millis - the length of time to sleep in milliseconds. millis - 以毫秒为单位的睡眠时间。
Throws : 抛出
InterruptedException - if any thread has interrupted the current thread . InterruptedException - 如果有任何线程中断了当前线程 The interrupted status of the current thread is cleared when this exception is thrown. 抛出此异常时,将清除当前线程的中断状态。

No exception will be thrown unless the sleeping thread is actually interrupted. 除非睡眠线程实际被中断, 否则不会抛出任何异常。 Here is a version of the code that more reliably tests the behavior you are examining: 这是一个代码版本,可以更可靠地测试您正在检查的行为:

Thread targetThread = new Thread() {
    @Override
    public void run() {
        try {
            Thread.sleep(5000);
            System.out.println("Target thread completed normally");
        } catch(final InterruptedException ie) {
            System.out.println("Target thread was interrupted");
        }
    }
};

targetThread.start();
targetThread.interrupt();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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