Java高并发编程学习--6. 线程的关闭

博客介绍了Java线程关闭的两种方式,一是捕获interrupt关闭线程,二是使用volatile开关控制,并提及了各自的执行结果。

一、捕获interrupt关闭线程

package mian;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName InterruptThreadExit
 * @Description TODO
 * JDK有一个Deprecated方法stop,但是该方法有一个问题
 * 该方法关闭线程时可能不会释放monitor的锁
 * 1. 捕获interrupt关闭线程
 * 2. volatile开关控制
 * @Author Cays
 * @Date 2019/3/11 10:56
 * @Version 1.0
 **/
public class InterruptThreadExit {
    public static void main(String []args) throws InterruptedException {
        Thread t=new Thread(){
            @Override
            public void run() {
                System.out.println("I will start work.");
                while (!isInterrupted()){
                    //System.out.println("working...");
                }
                System.out.println("I will be exiting.");
            }
        };
        t.start();
        TimeUnit.SECONDS.sleep(5);
        System.out.println("System will be shutdown.");
        t.interrupt();
        //通过检查线程interrupt标识来决定是否退出
        //执行可中断方法,可捕获中断信号退出
    }
}

执行结果:
在这里插入图片描述

二、volatile开关控制

package mian;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName FlagThreadExit
 * @Description TODO
 * volatile开关控制
 * @Author Cays
 * @Date 2019/3/11 11:03
 * @Version 1.0
 **/
public class FlagThreadExit {
    static class MyTask extends Thread{
        private volatile boolean close=false;
        //volatile是java原子变量以及并发包的基础
        @Override
        public void run() {
            System.out.println("I will start work");
            while (!close&&!isInterrupted());
            System.out.println("I will be exit.");
        }
        public void close(){
            this.close=true;
            this.interrupt();
        }
    }
    public static void main(String []args) throws InterruptedException {
        MyTask t=new MyTask();
        t.start();
        TimeUnit.SECONDS.sleep(3);
        System.out.println("System will be shutdoewn.");
        t.close();
    }
}

执行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值