JDK多线程之线程的停止

线程停止的概述

1.首先,我们这里的说的线程的停止,主要是基于一个线程的具体的业务任务的完成;

线程停止的方式

1.Thread.stop()

概述

1.stop方式是一种不安全的停止方式,因为他会停止当前线程当中剩余的全部工作;
  所以很明显不符合我们上面的业务逻辑要求,因此是不推荐的,当前已经被废弃的方法;

2.使用volatile修饰的Filed字段

1.使用volatile修饰字段,根据被修饰字将STOP_FLAG的值判断,是否进行线程的终止;
2.备注:volatile修饰的字段,在多线程运行的过程中是所有线程共享的变量;
  因此一个线程将STOP_FLAG设置为true,那么新加入的线程不会再执行业务处理;
package com.gaoxinfu.demo.jdk.rt.java.lang.thread;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: gaoxinfu
 * @Date: 2020-05-15 17:00
 */
public class VolatileDemo {

    private volatile static boolean STOP_FLAG =Boolean.FALSE;

    public static void main(String[] args) throws InterruptedException {

        Long start=System.currentTimeMillis();
        Thread thread=new Thread(()->{
            if(!STOP_FLAG){
                System.out.println("对不起我这个线程已经停止服务了");
            }
        });
        thread.start();;
        TimeUnit.SECONDS.sleep(1l);
        VolatileDemo.STOP_FLAG =Boolean.TRUE;
        System.out.println("start = "+new Date(start));
        System.out.println("stop  = "+new Date(System.currentTimeMillis()));

    }
}

3.使用线程Thread.interrupt()方法

1.interrupt()方法会将当前线程执行完成之后,终止该线程,因此是安全的;
package com.gaoxinfu.demo.jdk.rt.java.lang.thread;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: gaoxinfu
 * @Date: 2020-05-15 16:48
 */
public class InterruptDemo {


    public static void main(String[] args) throws InterruptedException {
        Long start=System.currentTimeMillis();
        Thread thread=new Thread(()->{
            while (!Thread.currentThread().interrupted()){
                for (int j = 0; j <100; j++) {
                    System.out.println("j =" +j);
                }
            }
        });
        thread.start();
        TimeUnit.SECONDS.sleep(1l);
        thread.interrupt();
        System.out.println(thread.isInterrupted());
        System.out.println("start = "+new Date(start));
        System.out.println("stop  = "+new Date(System.currentTimeMillis()));
    }
}

这里大家注意下,Interrupted()方法的调用本质上也是一个打标行为,然后再次判断标记状态
你像join sleep wait等方法被调用后,我们也可以通过Interrupted()去处理

interrupt 设置一个标记行为

interrupt也会唤醒线程

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东山富哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值