【问题标题】:Why do I need to handle an exception for Thread.sleep()?为什么我需要处理 Thread.sleep() 的异常?
【发布时间】:2014-12-29 11:09:20
【问题描述】:

要编译这段代码,我可以:

为什么我必须这样做?

class Test {
    public static void main( String[] args ) {
          printAll( args );
    }

    public static void printAll( String[] line ) {
        System.out.println( lines[ i ] );
        Thread.currentThread().sleep( 1000 ):
    }
}

(来自Kathy Sierra's SCJP book的示例代码。)

我知道Thread.sleep()抛出的异常是受检异常,所以我要处理它,但是Thread.sleep()在什么情况下需要抛出这个异常呢?

【问题讨论】:

  • 因为 Sleep 方法检查了异常...
  • 感谢您的重播,我知道这个检查异常,但是为什么在什么情况下我们需要处理异常呢?

标签: java multithreading exception


【解决方案1】:
 class Demo extends Thread{
    public void run() {
        for (int i = 0; i <10; i++) {
        system.out.println("hello Ziyad");
        thread.sleep(1000);
    }} }
            public class Threddemo{
        public static void main(string[] args) throws interruptedexception {
            Demo t=new Demo();
            Demo t2=new Demo();
        t.start();
        t2.start();
            }}

假设我们有两个线程 t 和 t2,t 正在执行,t2 来了,t2 也开始执行,但 t 还没有完成 那里的线程被中断,你丢失了你的数据。在上面的例子中,t 线程正在运行并且处于睡眠模式时,t2 来了 并开始突然执行 t 起床但 t2 正在运行这是中断异常的机会和数据丢失以避免这种情况我们使用中断异常

【讨论】:

    【解决方案2】:

    如果一个方法的声明方式可以抛出检查异常(Exceptions 不是RuntimeException 的子类),调用它的代码必须在try-catch 块或调用者方法中调用它必须声明扔掉它。

    Thread.sleep() 声明如下:

    public static void sleep(long millis) throws InterruptedException;
    

    它可能会抛出 InterruptedException 直接扩展 java.lang.Exception 所以你必须抓住它或声明抛出它。

    为什么Thread.sleep() 是这样声明的?因为如果 Thread 正在休眠,则线程可能会被中断,例如Thread.interrupt() 由另一个线程在这种情况下,休眠线程(sleep() 方法)将抛出此 InterruptedException 的一个实例。

    示例:

    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                System.out.println("Sleeping...");
                Thread.sleep(10000);
                System.out.println("Done sleeping, no interrupt.");
            } catch (InterruptedException e) {
                System.out.println("I was interrupted!");
                e.printStackTrace();
            }
        }
    };
    t.start();     // Start another thread: t
    t.interrupt(); // Main thread interrupts t, so the Thread.sleep() call
                   // inside t's run() method will throw an InterruptedException!
    

    输出:

    Sleeping...
    I was interrupted!
    java.lang.InterruptedException: sleep interrupted
        at java.lang.Thread.sleep(Native Method)
        at Main$1.run(Main.java:13)
    

    【讨论】:

    • @UnKnown 相反,我们不应该中断线程。一种常见的技术是通知线程它应该结束其运行,并且线程本身应该监视是否发出了这样的请求(如果是,则通过从 run() 方法返回来优雅地终止)。
    • Thread.sleep 有可能出现异常,IMO,糟糕的 API 设计
    【解决方案3】:

    一个Thread 可以与另一个Thread 通信和交互,一种方法是中断它:如果t 是另一个Thread,您可以致电t.interrupt() 询问它礼貌地停止它目前正在做的事情。如果t 正在睡觉,这尤其是您可能想要做的事情:您可能想要唤醒它。它的作用是在tThread.sleep() 方法中引发InterruptedException,以便它可以捕获并响应。因此,每当您使用Thread.sleep() 使当前线程进入睡眠状态时,您都必须处理InterruptedException 的可能性,以防另一个线程决定唤醒它。

    在你的例子中,你只有一个Thread,所以你知道你的代码中不能有来自其他地方的InterruptedException。但在多线程代码中想要做的事情并不少见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 2010-12-19
      • 2012-11-16
      相关资源
      最近更新 更多