您的位置:首页 > 其它

中断线程的方法

2017-05-14 16:50 218 查看
尊重个人劳动成果,转载请注明出处:

http://blog.csdn.net/czd3355/article/details/72026801

异常法【推荐】

public class Run {
public static void main(String[] args) {
try {
StopThread01 thread01 = new StopThread01();
thread01.start();
Thread.sleep(1000);
thread01.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("main end");
}
}

public class StopThread01 extends Thread {
@Override
public void run() {
super.run();
try {
for (int i = 0; i < 500000; i++) {
if (Thread.interrupted()) {
System.out.println("子线程已经被标记为中断状态了。。。");
throw new InterruptedException();
}
System.out.println("i= " + i);
}
System.out.println("for 循环外部,若子线程没被停止则会执行该语句。。。");
} catch (InterruptedException e) {
System.out.println("run catch");
e.printStackTrace();
}
}
}


输出结果:



中断线程还有以下两种方法:

在 sleep 状态下中断线程

使用 return 中断线程

但由于与异常法相比稍逊一筹,所以在此也就不再多介绍了。详细可参考《java多线程编程核心技术》第一章
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: