java interrupt()方法只是设置线程的中断标记,当对处于阻塞状态的线程调用interrupt方法时(处于阻塞状态的线程是调用sleep, wait, join 的线程),会抛出InterruptException异常,而这个异常会清除中断标记。因此,根据这两个思路,不同的run()方法设计,会导致不同的结果,下面是示例,并说明了运行了结果和原因
package com.concurrency;
import java.util.concurrent.TimeUnit;
public class Test{
public static void main(String[] args) throws InterruptedException {
RunTest rt = new RunTest();
Thread t = new Thread(rt);
t.start();
TimeUnit.SECONDS.sleep(2);
t.interrupt();
}
}
class RunTest implements Runnable{
public void run1(){
try{
while(!Thread.interrupted()){
}
System.out.println("Exit normal");
}catch(Exception e){
System.out.println("interrupted");
}
}
public void run5() {
try{
while(!Thread.interrupted()){
Thread.sleep(5000);
}
System.out.println("Exit normal");
}catch(Exception e){
System.out.println("interrupted and exit");
}
}
public void run3(){
while(!Thread.interrupted()){
}
System.out.println("interrupt normal and exit 2");
}
public void run4(){
while(!Thread.interrupted()){
try{
TimeUnit.SECONDS.sleep(1);
}catch(Exception e){
System.out.println("Interrupte and clear interrupt status, so run continue");
}
}
System.out.println("exit normal 3");
}
public void run(){
double d = 1;
while(!Thread.interrupted()){
while(d<3000){
d = d + (Math.PI+Math.E)/d;
System.out.println(d+ " running");
}
}
System.out.println("Exit "+d);
}
}
可以将run()改为上面其中的一个,对比看看运行结果,如上面所述。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)