在线程的情况下Thread.sleep和wait()方法的异常处理

Sun*_*pta 6 java multithreading exception-handling

我试图编写一个Producer Consumer模型(java中的Producer线程和Consumer Thread)

我想知道如何处理方法和类的方法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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我采取的一个例子,在这个例子中,可能没有必要处理这些异常(我的假设).

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

Gra*_*ray 11

我想知道如何处理Thread.sleep方法和Object Class的wait方法抛出的中断Exception

有两件重要的事情需要实现InterruptedException.首先,当它被抛出时,中断标志Thread被清除.所以你应该总是这样做:

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

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

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

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

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