当一个线程运行时,另一个线程可以调用对应的Thread对象的interrupt()方法来中断它。
package ThreadTest;
public class SleepInterrupt implements Runnable{
public void run(){
try{
System.out.println("在run()方法中-这个线程休眠20秒");
Thread.sleep(2000);
System.out.println("在run()方法中-继续运行");
}catch(InterruptedException e){
System.out.println("在run()方法中-中断线程");
return;
}
System.out.println("在run()方法中-休眠之后继续运行");
System.out.println("在run()方法中-正常退出");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SleepInterrupt si = new SleepInterrupt();
Thread t = new Thread(si);
t.start();
//在此休眠是确保线程能多运行一会
try{
Thread.sleep(2000);
}catch(InterruptedException e){}
System.out.println("在main()方法中-中断其它线程");
t.interrupt();
System.out.println("在main()方法中-退出");
}
}
本文通过一个具体的Java示例展示了如何使用Thread类的interrupt方法来中断一个正在运行的线程。示例中的SleepInterrupt类实现了Runnable接口并在其run方法中使用了Thread.sleep来模拟线程休眠,并捕获InterruptedException来响应中断请求。
319

被折叠的 条评论
为什么被折叠?



