我经历的凯西塞拉利昂SCJP 1.5第9章(线程)它就在那里提到:需要示例程序抛出InterruptedException
注意,sleep()方法可以抛出一个检查InterruptedException异常 (你通常就会知道,如果这是一个可能性,因为另一个线程必须明确做 中断),所以你必须承认的例外与手柄或声明
我只是需要一个示例程序就知道当它h (我可以在我的机器上运行)?
我用Google搜索,但没有找到任何的示例代码来测试此功能..
由于提前
我经历的凯西塞拉利昂SCJP 1.5第9章(线程)它就在那里提到:需要示例程序抛出InterruptedException
注意,sleep()方法可以抛出一个检查InterruptedException异常 (你通常就会知道,如果这是一个可能性,因为另一个线程必须明确做 中断),所以你必须承认的例外与手柄或声明
我只是需要一个示例程序就知道当它h (我可以在我的机器上运行)?
我用Google搜索,但没有找到任何的示例代码来测试此功能..
由于提前
下面是一个例子:
public class Test
{
public static void main (String[] args)
{
final Thread mainThread = Thread.currentThread();
Thread interruptingThread = new Thread(new Runnable() {
@Override public void run() {
// Let the main thread start to sleep
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
mainThread.interrupt();
}
});
interruptingThread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("I was interrupted!");
}
}
}
要穿行:
主线程中的睡眠不是严格的必要的,但它意味着主线程在被中断之前确实开始睡眠。
谢谢琼你的及时答案.. 只是好奇知道有什么办法,通过它我们可以导致interruptedexception,除中断方法? – javanoob 2010-09-04 13:17:54
@javanoob:不是我知道的......其他方法当然可以调用'interrupt()',所以你的代码可能不会显示'interrupt()'被调用,但基本上是这样的你中断了这个线程。 – 2010-09-04 17:12:46
public class SleepTest1 extends Thread {
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
Thread.currentThread().interrupt();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SleepTest1 st1 = new SleepTest1();
st1.start();
}
}
代码只有堆栈溢出时才皱起眉头。你能扩展这个答案吗? – 2016-08-30 09:59:10
该代码不会中断睡眠,睡眠后会中断。这不是OP所要求的。 – 2016-08-30 10:20:36
这篇文章可能会有所帮助:你是做什么用InterruptedException的?](http://www.yegor256.com/2015/10/20/interrupted-exception.html) – yegor256 2017-05-18 10:54:57