java Thread.sleep 的异常处理和 Threads 的 wait() 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10317041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:32:49  来源:igfitidea点击:

Exception Handling in case of Thread.sleep and wait() method in case of Threads

javamultithreadingexception-handling

提问by Sunny Gupta

I was trying to write a Producer Consumer model (Producer thread and Consumer Thread in java)

我正在尝试编写一个生产者消费者模型(Java 中的生产者线程和消费者线程)

I was wondering how to handle the InterruptedExceptionthat is thrown by Thread.sleepmethod and the ObjectClass's wait()method

我想知道如何处理方法和类的方法InterruptedException抛出的Thread.sleepObjectwait()

package producerconsumer;

import java.util.ArrayList;

public class Consumer implements Runnable {

    ArrayList<Integer> container;

    @Override
    public void run() {
        while(true){
        System.out.println("Consumer Thread Running");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(null==container){
            System.out.println("container is null");
        }
        //Removing values from Arraylist
        synchronized (container) {
            if(container.size()==0){
                try {
                    container.wait();
                } catch (InterruptedException e) {
                    //How to tackle this exception
                    e.printStackTrace();
                }
            }
            Integer removedInteger = container.remove(container.size()-1);
            System.out.println("removedInteger..."+removedInteger);
        }
        }
    }

    public void setContainer(ArrayList<Integer> container) {
        this.container = container;
    }
}

This is one example I have taken, In this example there may not be any need to take care of these exception (My Assumption).

这是我采取的一个例子,在这个例子中,可能不需要处理这些异常(我的假设)。

But I wanted to know what could be the different scenarios possible in which we need to handle this exception.

但我想知道我们需要处理这个异常的不同场景可能是什么。

回答by Gray

I was wondering how to handle the interrupted Exception that is thrown by Thread.sleep method and the Object Class's wait method

我想知道如何处理 Thread.sleep 方法和对象类的 wait 方法抛出的中断异常

There are two important things to realize about InterruptedException. First off, when it is thrown the interrupt flag on the Threadis cleared. So you should always do something like:

有两件重要的事情需要意识到InterruptedException。首先,当它被抛出时,中断标志Thread被清除。因此,您应该始终执行以下操作:

} catch (InterruptedException e) {
    // re-add back in the interrupt bit
    Thread.currentThread().interrupt();
    ...
}

This is a very important pattern because it allows other code that might be calling yours to detect the interrupt as well.

这是一个非常重要的模式,因为它允许其他可能调用您的代码的代码也检测中断。

Secondly, in terms of threads, if they are interrupted, they should most likely cleanup and quit. This is certainly up to you, the programmer, but the general behavior is to terminate and quit the operation being performed – often because the program is trying to shutdown.

其次,就线程而言,如果它们被中断,它们很可能应该清理并退出。这当然取决于您,程序员,但一般行为是终止并退出正在执行的操作 - 通常是因为程序试图关闭。

} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    // we are being interrupted so we should stop running
    return;
}

Lastly, with any exception handling, the default Eclipse template is usually the wrongthing to do. Never just e.printStackTrace();the exception. Figure out what you want to do with it: re-throw it as another exception, log it somewhere better, or exit the thread/method/application.

最后,对于任何异常处理,默认的 Eclipse 模板通常是错误的。从不只是e.printStackTrace();例外。弄清楚你想用它做什么:将它作为另一个异常重新抛出,将它记录在更好的地方,或者退出线程/方法/应用程序。