错误用例

下面用例中,一个正在sleep的线程,在调用interrupt后,wait方法检查到isInterrupted()为true,抛出异常, 而catch到异常后没有处理。一个抛出了InterruptedException的线程的在调用interrupt后状态马上就会被置为非中断状态。如果catch语句没有处理异常,则下一 次循环中isInterrupted()为false,线程会继续执行,程序无法正常退出。

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SparkStreamThread implements Runnable { public void stopStream() {
this.log.warn("Stop Stream!!");
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + "将要运行...");
while (!Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName() + "运行中");
try {
Thread.sleep(400);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "从阻塞中退出...");
System.out.println("this.isInterrupted()=" + Thread.currentThread().isInterrupted());
}
}
System.out.println(Thread.currentThread().getName() + "已经终止!");
} public static void main(String argv[]) throws InterruptedException {
Thread ta = new Thread(new SparkStreamThread());
ta.start();
Thread.sleep(2000);
System.out.println(ta.getName() + "正在被中断...");
ta.interrupt();
System.out.println("ta.isInterrupted()=" + ta.isInterrupted());
}
}

正确用例1,异常捕获后终止线程

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SparkStreamThread implements Runnable { public void stopStream() {
this.log.warn("Stop Stream!!");
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + "将要运行...");
while (!Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName() + "运行中");
try {
Thread.sleep(400);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "从阻塞中退出...");
Thread.currentThread().interrupt();
System.out.println("this.isInterrupted()=" + Thread.currentThread().isInterrupted());
}
}
System.out.println(Thread.currentThread().getName() + "已经终止!");
} public static void main(String argv[]) throws InterruptedException {
Thread ta = new Thread(new SparkStreamThread());
ta.start();
Thread.sleep(2000);
System.out.println(ta.getName() + "正在被中断...");
ta.interrupt();
System.out.println("ta.isInterrupted()=" + ta.isInterrupted());
}
}
 

正确用例2, 使用变量,double check,二次检查

public class ThreadA extends Thread {
private boolean isInterrupted=false;
int count=0; public void interrupt(){
isInterrupted = true;
super.interrupt();
} public void run(){
System.out.println(getName()+"将要运行...");
while(!isInterrupted){
System.out.println(getName()+"运行中"+count++);
try{
Thread.sleep(400);
}catch(InterruptedException e){
System.out.println(getName()+"从阻塞中退出...");
System.out.println("this.isInterrupted()="+this.isInterrupted()); }
}
System.out.println(getName()+"已经终止!");
}
}

Java——安全地停止线程的更多相关文章

  1. Java如何停止线程?

    在Java编程中,如何停止线程? 以下示例演示了如何通过创建一个用户定义的方法run()方法和Timer类来停止线程. package com.yiibai; import java.util.Tim ...

  2. 深入理解Java中停止线程

    一.停止线程会带来什么? 对于单线程中,停止单线程就是直接使用关键字return或者break,但是在停止多线程时是让线程在完成任务前去开启另外一条线程,必须放弃当前任务,而这个过程是不可预测,所以必 ...

  3. 转: Java安全停止线程方法

    转: http://blog.csdn.net/flyingpig4/article/details/7675557 1.早期Java提供java.lang.Thread类型包含了一些列的方法star ...

  4. Java安全停止线程方法

    1. 早期Java提供java.lang.Thread类型包含了一些列的方法 start(), stop(), stop(Throwable) and suspend(), destroy() and ...

  5. java安全停止线程

    Thread.stop()是一个被废弃的方法,不被推荐使用的原因是stop方法太过于暴力,强行把执行到一半的线程终止,并且会立即释放这个线程所有的锁.会破坏了线程中引用对象的一致性. 使用判断标志位的 ...

  6. Java并发编程的艺术(六)——中断、安全停止线程

    什么是中断 Java的一种机制,用于一个线程去暂停另一个线程的运行.就是一个正在运行的线程被其他线程给打断,停止运行挂起了. 我觉得,在Java中,这种中断机制只是一种方便程序员编写进程间的通信罢了. ...

  7. java线程之停止线程

         在Java中有以下3种方法可以终止一个正在运行的线程:      1.使用退出标志,是线程正常退出,也就是run方法完成后线程终止.      2.使用stop方法强制终止线程,但不推荐使用 ...

  8. JAVA之旅(十五)——多线程的生产者和消费者,停止线程,守护线程,线程的优先级,setPriority设置优先级,yield临时停止

    JAVA之旅(十五)--多线程的生产者和消费者,停止线程,守护线程,线程的优先级,setPriority设置优先级,yield临时停止 我们接着多线程讲 一.生产者和消费者 什么是生产者和消费者?我们 ...

  9. java中线程的几种状态和停止线程的方法

    1.线程的状态图 需要注意的是:线程调用start方法是使得线程到达就绪状态而不是运行状态 2.停止线程的两种方法 1)自然停止:线程体自然执行完毕 2)外部干涉:通过线程体标识 1.线程类中定义线程 ...

随机推荐

  1. WinForm timer 控件

    timer 控件:按用户定义的时间间隔引发的事件 属性: Enabled 是否启用: Interval 事件发生的事件间隔,单位是毫秒 事件只有一个:Tick 事件经过指定的时间间隔发生 打开一个窗口 ...

  2. BZOJ.4542.[HNOI2016]大数(莫队)

    题目链接 大数除法是很麻烦的,考虑能不能将其条件化简 一段区间[l,r]|p,即num[l,r]|p,类似前缀,记后缀suf[i]表示[i,n]的这段区间代表的数字 于是有 suf[l]-suf[r+ ...

  3. PHP函数 ------ ctype_alnum

    //判断是否是字母和数字或字母数字的组合 if(!ctype_alnum($str)){ echo '只能是字母或数字的组合';exit; }整理下ctype functions: 1.ctype_a ...

  4. php 字符串翻转

    字符串翻转 <?php$s = 'strlen,substr,count';$o = '';$i = 0;while(isset($s[$i]) && $s[$i] != nul ...

  5. 潭州课堂25班:Ph201805201 爬虫基础 第十课 图像处理- 极验验证码 (课堂笔记)

    用 python 的  selenium  访问  https://www.huxiu.com/ 自动通过验证码 # -*- coding: utf-8 -*- # 斌彬电脑 # @Time : 20 ...

  6. java后端发送请求

    package com.ty.mapapisystem.util; import java.io.BufferedReader;import java.io.FileInputStream;impor ...

  7. 添加 vip

    两台机器:172.16.91.101 172.16.91.107 在91.101上增加虚拟ip,92网段的 ifconfig eth0:1 172.16.92.2 netmask 255.255.25 ...

  8. 使用Date和SimpleDateFormat类表示时间

    Date类: 使用 Date 类的默认无参构造方法创建出的对象就代表当前时间,我们可以直接输出 Date 对象显示当前的时间,显示的结果如下: Date d = new Date(); System. ...

  9. VS2008中捕获内存泄露(转)

    内存泄露十分讨厌,捕获内存泄露更加令人厌烦…… 其实,VS本身就有内存泄露的检测机制.只需做以下操作即可开启.(同时必须在debug模式 下运行程序并且以 正常流程退出 ) // 在入口函数cpp中添 ...

  10. PID控制器(比例-积分-微分控制器)- V

    Linear Actuator - PID Control Introduction This application guide is designed to explain the basics ...