java中止运行线程

java线程中止有三种方式:

  1. 直接使用stop()方法,已经弃用,不建议使用。
  2. 自定义volatile boolean类型变量作为中止标识。
package stop;

public class ThreadStop1 {
     public static class MyThread extends Thread{
         private volatile boolean start=true;
         @Override
         public void run() {
             while(start){
                 doTask();
             }

         }
         private void doTask(){
             System.out.println("do some work");
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
         private void shutDown(){
             start=false;
         }
     }

    public static void main(String[] args) {
        MyThread t1=new MyThread();
        t1.start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.shutDown();
    }
}

  1. 使用interrupted()方法
    Thread.currentThread().interrupted()获取线程的中断标志,并重置。isInterrupted() 获取线程中断标志,不重置。interrupt()将目标线程的中断标记设置为true,在一些catch InterruptedException的方法中抛出异常。

下面看一个小栗子:
可以想一下程序打印的结果,他会打印after吗?

public class StopTest {

    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            System.out.println("before");
//            if (!Thread.interrupted()){
                System.out.println("in");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace(); 
                }
                System.out.println("after");
//            }
        });

        t.start();
        t.interrupt();
    }
}

来看下结果:线程还是会打印after,

改进一下:

ublic class StopTest {

    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            try {
                System.out.println("before");
                Thread.sleep(100);
                if (!Thread.interrupted()) {
                    System.out.println("in");
                    Thread.sleep(2000);
                    System.out.println("after");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println();
            }
        });

        t.start();
        t.interrupt();
    }
}

有错误还请指出!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值