Thread 类中的中断方法:
public boolean isInterrupt() 测试线程是否中断。
public viod interrupt() 中断线程。
package ThreadInterrupt;
public class ThreadInterruptDemo implements Runnable{
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Thread thread =new Thread(new ThreadInterruptDemo(),"Mythread");
thread.start();
Thread.sleep(1000);
System.out.println("interrupt Mythread");
thread.interrupt(); //中断线程
System.out.println("Mythread 是否中断:"+ thread.isInterrupted());
Thread.sleep(1000);
System.out.println("main 线程结束");
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<=5;i++){
System.out.println("Mythread第"+i+"次循环");
long time = System.currentTimeMillis();
while((System.currentTimeMillis()-time<1000)){// 循环持续1秒
}
}
System.out.println("Mythread 已经被结束");
}
}
运行结果如下;
interrupt() 被使用 ,线程Mythread 被中断 ,但并没有停止。
需要使用isInterrupt()对中断进行处理。
在 for循环里面加入如下代码:
if(Thread.currentThread().isInterrupted()){
break;
}
运行结果如下:
线程Mythread 成功结束。