割り込み
あるスレッドがwait(),join(),sleep()メソッドで一時停止している場合、別スレッドから、Threadクラスの interrupt() メソッドを実行することにより一時停止状態から復帰して処理続行させることができます。 これを割り込みと言います。
この時、wait(),join(),sleep()メソッドは例外InterruptedExceptionをthrowします。
以下、例を見てください。

TESTクラス
public class TEST{
    public static void main(String[] args){
        MyThread th = new MyThread();
        th.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        th.interrupt();
    }
}
上記例では、main()メソッドでスレッドを作成し、そのスレッドを実行しています。そして1秒後に割り込みをしています。 MyThreadクラスは以下のとおりです。

MyThreadクラス
public class MyThread extends Thread{
    Object obj = new Object();
    
    public void run(){
        synchronized(obj){
            try {
                obj.wait();
            } catch (InterruptedException e) {
                System.out.println("throw InterruptedException.");
            }
        }
        System.out.println("end.");
    }
}
TESTクラスを実行すると、一時停止状態になっているthインスタンスに対して、interrupt()メソッドを実行したため、wait()メソッドは例外InterruptedExceptionをthrowします。

実行結果は以下のとおりになります。

throw InterruptedException.
end.

Back to top

Information