多线程:线程终止
线程终止
interrupt()设置线程中断标志,默认值为False
(无法打断该线程的执行,但是可以获得该线程被中断的标志,interrupted()得到true, 判断中断)标志决定是否要终止线程。
MyThread.java
package test5;
public class MyThread extends Thread {
String name;
public MyThread(String name) {
super();
this.name = name;
}
public void run() {
System.out.println("线程"+this.name+"开始执行");
int i=0;
while(1==1) {
if(!Thread.currentThread().isInterrupted()) {
System.out.println(i);
i++;
}else {
System.out.println("执行结束");
return;
}
}
}
}
text.java
package test5;
public class test {
public static void main(String[] args) throws InterruptedException {
MyThread mt1=new MyThread("123");
System.out.println("设置终止前:"+mt1.isInterrupted());
mt1.start();
//10ms后将线程mt1的执行标准设置为ture
Thread.sleep(1);
mt1.interrupt();
System.out.println("设置终止后:"+mt1.isInterrupted());
}
}
执行结果:
设置终止前:false
线程123开始执行
0
1
2
3
..
...
....
218
219
220
执行结束
设置终止后:true
阅读剩余
版权声明:
作者:Tin
链接:http://www.tinstu.com/576.html
文章版权归作者所有,未经允许请勿转载。
THE END