java中如何靠interrupt來停止stop一個(gè)線程
停止(stop)一個(gè)線程(靠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();等于進(jìn)入到那個(gè)線程中,拋出一個(gè)InterruptedException異常。當(dāng)然那個(gè)線程的catch能捕獲到了*/
mt.interrupt();
}
}
輸出結(jié)果:
i = 0
i = 1
我被打斷
后續(xù):
馬克-to-win:本例中,主線程和子線程同時(shí)開始。主線程睡了250毫秒以后,開始打斷子線程。子線程每睡一百毫秒就打印一下。剛睡了兩次打印出0 和1以后,就被主線程打斷了。馬克-to-win:mt.interrupt(); 意味著進(jìn)入到mt那個(gè)線程中,拋出一個(gè)InterruptedException異常,這樣當(dāng)然mt那個(gè)線程的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("我被打斷");
return;
}
System.out.println(i++);
}
}
}
public class Test {
public static void main(String[] args) {
ThreadMark_to_win mt = new ThreadMark_to_win();
mt.start();
try {
Thread.sleep(25);
} catch (Exception e) {
e.printStackTrace();
}
/*mt.interrupt();等于進(jìn)入到那個(gè)線程中,拋出一個(gè)InterruptedException異常。當(dāng)然那個(gè)線程的catch能捕獲到了*/
mt.interrupt();
}
}
結(jié)果:
0
1
我被打斷
例:1.5.2_b:
class ThreadMark_to_win extends Thread {
public void run() {
int i=0;
while(true) {
System.out.println(i++);
}
}
}
public class Test {
public static void main(String[] args) {
ThreadMark_to_win mt = new ThreadMark_to_win();
mt.start();
try {
Thread.sleep(25);
} catch (Exception e) {
e.printStackTrace();
}
/*mt.interrupt();等于進(jìn)入到那個(gè)線程中,拋出一個(gè)InterruptedException異常。當(dāng)然那個(gè)線程的catch能捕獲到了*/
mt.interrupt();
}
}
結(jié)果:
0
1
2
3
4
5
。。。。。。。
661807
661808
661809
661810
661811
661812
。。。。。。。。。