| 目次 |
|---|
|
・割り込み ・TESTクラス ・MyThreadクラス ・実行結果 |
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クラスは以下のとおりです。
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.