トップページ >  Java >  割り込み
初版2006/09/06: 最終更新日2006/09/06
  割り込み
目次
割り込み
TESTクラス
MyThreadクラス
実行結果
割り込み
あるスレッドが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.


Information
リンクについて
個人情報保護方針
Yahoo!ブックマークに登録

社長&社員ブログ
やる気はあるがお金がない㈱コンフレッジブログ

slot大好きな㈱コンフレッジ社員のブログ
広告

サイト内検索
当サイト内を検索できます↓


PV