本文主要总结在java中停止线程的方法

在java中有以下三种方法可以终止正在运行的线程:

1、使用退出标志

2、使用stop方法强行终止线程,但是不推荐,因为stop和suspend、resume一样都是过时的方法

3、使用interrup方法中断线程

停止不了的线程

本例将使用interrupt方法来停止进程,看看效果:

public class MyThread extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 1234; i++) {
System.out.println("i=" + (i + 1));
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.interrupt(); } catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
}
}

可以看出,线程没有停止

判断线程是否是停止状态

在java的SDK中,Thread.java类里提供了两种方法:

(1)this.interrupted():测试当前线程是否已经中断

(2)this.isInterrupted():测试线程是否已经中断

首先看一下interrupted()

实战验证一下:

public class MyThread extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 10000; i++) {
System.out.println("i=" + (i + 1));
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
System.out.println("是否停止1?="+thread.interrupted());
System.out.println("是否停止2?="+thread.interrupted()); } catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}

运行结果如下:

.......................

i=9998
i=9999
i=10000
是否停止1?=false
是否停止2?=false
end!

由于interrupted是测试当前线程,当前线程为main,一直没有中断,所以返回两个false

将代码修改一下:

public class Run {
public static void main(String[] args) {
Thread.currentThread().interrupt();
System.out.println("是否停止1?=" + Thread.interrupted());
System.out.println("是否停止2?=" + Thread.interrupted());
System.out.println("end!");
}
}

返回如下信息:

是否停止1?=true
是否停止2?=false
end!

由于interrupted方法有清除状态的功能,所以第二次返回false

再看看isInterrupted()方法

public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
System.out.println("是否停止1?=" + thread.isInterrupted());
System.out.println("是否停止2?=" + thread.isInterrupted()); } catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}

运行结果:

i=123367
i=123368
是否停止1?=true
是否停止2?=true
i=123369
i=123370
i=123371
i=123372

总结:

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

(2)this.isInterrupted():测试线程是否已经中断,但不清除状态标志

能停止的线程--异常法

可以在线程中用for语句来判断一下线程是否是停止状态,如果是停止状态,则后面的代码不再运行即可

public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
for (int i = 0; i < 500000; 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.java类run方法中的catch了!");
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}

在sleep中停止

如果线程在sleep状态下停止线程,有什么效果呢?

public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
System.out.println("run begin");
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println("在沉睡中被停止!进入catch!" + this.isInterrupted());
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(200);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}

运行结果:

run begin
end!
在沉睡中被停止!进入catch!false
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.wuyudong.test1.MyThread.run(MyThread.java:9)

结果说明如果在sleep状态下停止线程,会进入catch语句,并且清除停止状态值,使之变成false

下面进行相反的操作,修改一下:

public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
for (int i = 0; i < 100000; i++) {
System.out.println("i=" + (i + 1));
}
System.out.println("run begin");
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println("先停止,再遇到了sleep!进入catch!");
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
thread.interrupt();
System.out.println("end!");
}
}

运行结果如下:

i=100000
run begin
先停止,再遇到了sleep!进入catch!
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.wuyudong.test1.MyThread.run(MyThread.java:12)

能停止的线程--暴力停止

使用stop方法停止线程是十分暴力的

public class MyThread extends Thread {
private int i = 0;
@Override
public void run() {
super.run();
try {
while (true) {
i++;
System.out.println("i=" + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("先停止,再遇到了sleep!进入catch!");
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(8000);
thread.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}

运行结果如下:

i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8

方法stop与异常

调用stop方法的时候会抛出java.lang.ThreadDeath异常,但是通常此异常不需要显式地捕捉

public class MyThread extends Thread {
private int i = 0;
@Override
public void run() {
super.run();
try {
while (true) {
i++;
System.out.println("i=" + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("先停止,再遇到了sleep!进入catch!");
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(8000);
thread.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}

使用return停止线程

将方法interrupt与return结合使用也能实现停止线程的效果

public class MyThread extends Thread {
private int i = 0;
@Override
public void run() {
super.run();
while(true){
if(this.isInterrupted()){
System.out.println("停止了!");
return;
}
System.out.println("timer="+System.currentTimeMillis());
}
}
}
public class Run {
public static void main(String[] args) throws InterruptedException{
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.interrupt();
} catch (Exception e) {
e.printStackTrace();
}
}
}

运行结果如下:

timer=1452841019023
timer=1452841019023
timer=1452841019023
timer=1452841019023
停止了!

java多线程系列7-停止线程的更多相关文章

  1. java多线程系列六、线程池

    一. 线程池简介 1. 线程池的概念: 线程池就是首先创建一些线程,它们的集合称为线程池. 2. 使用线程池的好处 a) 降低资源的消耗.使用线程池不用频繁的创建线程和销毁线程 b) 提高响应速度,任 ...

  2. (Java多线程系列二)线程间同步

    Java多线程间同步 1.什么是线程安全 通过一个案例了解线程安全 案例:需求现在有100张火车票,有两个窗口同时抢火车票,请使用多线程模拟抢票效果. 先来看一个线程不安全的例子 class Sell ...

  3. (Java多线程系列三)线程间通讯

    Java多线程间通讯 多线程之间通讯,其实就是多个线程在操作同一个资源,但是操作的动作不同. 1.使用wait()和notify()方法在线程中通讯 需求:第一个线程写入(input)用户,另一个线程 ...

  4. (Java多线程系列九)线程池

    线程池 1.什么是线程池 线程池是指在初始化一个多线程应用程序过程中创建一个线程集合,然后在需要执行新的任务时重用这些线程而不是新建一个线程.线程池中线程的数量通常取决于可用内存数量和应用程序的需求. ...

  5. Java多线程系列四——控制线程执行顺序

    假设有线程1/线程2/线程3,线程3必须在线程1/线程2执行完成之后开始执行,有两种方式可实现 Thread类的join方法:使宿主线程阻塞指定时间或者直到寄生线程执行完毕 CountDownLatc ...

  6. Java多线程系列三——实现线程同步的方法

    两种实现线程同步的方法 方法 特性 synchronized 不需要显式地加解锁,易实现 ReentrantLock 需要显式地加解锁,灵活性更好,性能更优秀,结合Condition可实现多种条件锁 ...

  7. java多线程系列8-线程的优先级

    在java中设置线程优先级使用setPriority,在jdk中的源代码如下: public final void setPriority(int newPriority) { ThreadGroup ...

  8. Java多线程系列十——BlockingQueue

    参考资料:http://ifeve.com/java-synchronousqueue/http://www.cnblogs.com/jackyuj/archive/2010/11/24/188655 ...

  9. Java多线程系列--“JUC线程池”01之 线程池架构

    概要 前面分别介绍了"Java多线程基础"."JUC原子类"和"JUC锁".本章介绍JUC的最后一部分的内容——线程池.内容包括:线程池架构 ...

随机推荐

  1. MFC ADO连接Oracle12c数据库 服务端配置

    要想客户端访问服务器端的oracle数据库的话,还需要服务端设置下监听程序及本地网络服务名配置. 发现百度文库上面有这方面的文档,我就不重复写了.请参照一下网址: http://wenku.baidu ...

  2. jquery getJSON

    function onNodeClick(data) {            //只能选择体检分组            if (data.GroupType == 1) {             ...

  3. android小技巧和注意事项

    在listView 或者 gridView 的使用中,通常不仅仅为了展现数据,更多的是操作数据.于是当控件重合在一起时,我们需要添加事件.就会出现一个问题,当点击一个控件和长按这个控件时,常常出现长按 ...

  4. “康园圈--互联网+校园平台“项目之sprint2

    一.sprint2任务列表 1.部署框架,并上传代码到github. 2.原型设计 * 设计首页界面原型(包括功能公告.快速通道等展示栏) * 设计店铺浏览页面原型 * 设计店内浏览页面原型 * 设计 ...

  5. spring日记------部署环境、写demo

    一.安装jdk1.7 祥见http://zhinan.sogou.com/guide/detail/?id=1610006590 二.创建web项目 略 三.配置ssm环境 3.1添加spring.m ...

  6. 三分 --- POJ 3301 Texas Trip

    Texas Trip Problem's Link:   http://poj.org/problem?id=3301 Mean: 给定n(n <= 30)个点,求出包含这些点的面积最小的正方形 ...

  7. Linq之group子句

    在Linq查询语句中,group子句主要作用是对查询的结果集进行分组.并返回元素类型为IGrouping<TKey,TElement>的对象序列. 下面我们在代码实例中创建一个GroupQ ...

  8. JavaScript异常捕获

    理论准备 ★   异常捕获 △ 异常:当JavaScript引擎执行JavaScript代码时,发生了错误,导致程序停止运行: △ 异常抛出:当异常产生,并且这个异常生成一个错误信息: △ 异常捕获: ...

  9. H5案例学习笔记

    ★基础篇     增加主体结构元素    

  10. jquery实现全选功能

    主要是模拟一些网页中的表格实现全选功能. <form> 你爱好的运动是: <input type="checkbox" id="Check" ...