HOME> Javaアプリケーション講座> スレッド>スレッドの割り込み

スレッドの割り込み

sleep()メソッドやjoin()メソッドの待ち状態の時に割り込みをかけます。

割り込みをかけるメソッドがinterruptメソッドです。

割り込まれたスレッドは例外interruptedException例外がスローされます。
そのため今までsleep()メソッドやjoin()メソッドを使用するときにはtry-catchブロックを定義していたのです。 図で説明します。

流れ的にはこの図のようになります。
ではサンプルプログラムを見ていきます。

サンプルプログラム(Sample108.java)

//割り込みされるスレッド

class InterruptSample extends Thread{
    public void run(){
   for(int i = 0; i < 12;i++){
     try{
        System.out.print(".");
        Thread.sleep(1000);
  }catch(InterruptedException e){

   //割り込まれたときの処理
     System.out.println("今割り込まれました");
             }
        }
    }
}
class Sample108{
    public static void main(String args[]){

    InterruptSample obj = new InterruptSample();
    obj.start();

    for(int j = 0;j < 6; j++){

   try{
      //2秒間隔で割り込みます
      Thread.sleep(2000);

     //InterrptSampleスレッドに割り込み

       obj.interrupt();

  }catch(InterruptedException e){}
      
       }
} }

プログラムをコピーする場合すべて選択をクリックしてください。

Sponsored link

コンパイル・実行します。

このようになります。InterruptSampleスレッドに割り込まれているのがわかります。

ページのトップへ戻る