您的位置 首页 java

java中如何靠interrupt来停止stop一个线程

停止(stop)一个线程(靠interrupt手段)

例:1.5.2-本章源码
class ThreadMark_to_win extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(“我被打断”);
return;
}
System.out.println(“i = ” + i);
}
}
}
public class Test {
public static void main(String[] args) {
ThreadMark_to_win mt = new ThreadMark_to_win();
mt.start();
try {
Thread.sleep(250);
} catch (Exception e) {
e.printStackTrace();
}
/*mt.interrupt();等于进入到那个线程中,抛出一个InterruptedException异常。当然那个线程的catch能捕获到了*/
mt.interrupt();
}
}

输出结果:

i = 0
i = 1
我被打断

后续:

马克-to-win:本例中,主线程和子线程同时开始。主线程睡了250毫秒以后,开始打断子线程。子线程每睡一百毫秒就打印一下。刚睡了两次打印出0 和1以后,就被主线程打断了。马克-to-win:mt.interrupt(); 意味着进入到mt那个线程中,抛出一个InterruptedException异常,这样当然mt那个线程的catch能捕获到了。
下面的例子证明,如果在子线程中开始不用
try {
Thread.sleep(100);
} catch (InterruptedException e) {
。。。。,

则主线程光靠mt.interrupt();是打断不了子线程的。

InterruptedException还可以用以下wait方法用,或和join方法一起用

try {
wait();
} catch (InterruptedException e) {
}
例:1.5.2_a:
class ThreadMark_to_win extends Thread {
public void run() {
int i=0;
while(true) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.out.println(“我被打断”);

篇幅有限更多请见扩展链接:

文章来源:智云一二三科技

文章标题:java中如何靠interrupt来停止stop一个线程

文章地址:https://www.zhihuclub.com/182634.shtml

关于作者: 智云科技

热门文章

网站地图