当一个线程运行时,另一个线程可以调用对应的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()方法中-退出");
}
}