您的位置:首页 > 编程语言 > Java开发

线程停止

2016-05-14 15:03 399 查看
在java中有以下三种方法可以终止正在运行的线程:

1)使用退出标志,是线程正常退出,即run方法完成后线程终止

2)使用stop()方法强行终止线程(不推荐使用)

3)使用interrupt()方法中断线程

使用interrupt方法终止线程 :

主要方法:1.interrupt():调用interrupt()方法仅仅在当前线程中打了一个停止的标记,并不是真的停止线程

2.interrupted():测试当前线程是否已经是中断状态,执行后具有将状态标志清除为false的功能

3.isInterrrupted():测试线程是否已经是中断状态,但不清除状态

例:使用interrupt异常法终止线程

public class MyThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
try{
for(int i=0;i<5000;i++){
if(this.interrupted()){
System.out.println("已经是停止状态了!我要退出!");
throw new InterruptedException();

}
System.out.println("i="+(i+1));

}
System.out.println("我在for下面");
}
catch(InterruptedException e){
System.out.println("进入MyThread类run方法中的catch了");
e.printStackTrace();
}
}
}

public class Run {

public static void main(String[] args) {
// TODO Auto-generated method stub
try{
MyThread thread=new MyThread();
thread.start();
Thread.sleep(2);
thread.interrupt();
}catch(InterruptedException e){
System.out.println("main catch");
e.printStackTrace();
}

}

}


运行结果:

.

.

.

i=93

i=94

i=95

i=96

i=97

i=98

i=99

i=100

i=101

i=102

i=103

i=104

已经是停止状态了!我要退出!

进入MyThread类run方法中的catch了

java.lang.InterruptedException

at com.cn.thread.MyThread.run(MyThread.java:12)

注意:如果线程在sleep()状态下停止线程,会出现异常,若果线程在interrupt()状态在遇到sleep(),不会出现异常
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 线程 线程停止