外部线程停止Java子线程的方法

一、Thread.stop()
官方不推荐,Because it is inherently unsafe.


二、方式一
1. 线程类示例

public class ThreadT1 implements Runnable {
    private Thread threadThis;

    public void start() {
        threadThis = new Thread(this);
        threadThis.start();
    }

    public void stop() {
        threadThis = null;
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (threadThis == thisThread) {
        System.out.println("lalala~ ");
        // DO YOUR WORK !
    }
    System.out.println("stopped!!!");
    }
}
            


2. 使用示例

ThreadT1 th1 = new ThreadT1();
th1.start(); //新建线程并启动
th1.stop(); //停止这个线程


三、方式二
1. 线程类示例

public class ThreadT2 extends Thread {
    private boolean stop = false;

    public void stopByMark() {
        stop = true;
    }

    public void run() {
        while (!stop) {
        System.out.println("lalala~ ");
        // DO YOUR WORK !
    }
    System.out.println("stopped!!!");
    }

}


2.使用示例

ThreadT2 th2 = new ThreadT2();
th2.start(); //新建线程并启动
th2.stopByMark(); //停止这个线程


附、关于Thread.interrupt()
通过这个方式也能停止线程。
前提条件:

public void run(){
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) { //必须存在捕获InterruptedException的方法,且发生了该    抛出就调用stop方法。
    e.printStackTrace();
    stopByMark();
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值