线程中断方法

在早期,我们使用stop方法终止线程
但此方法已经过时,因为强制杀死线程,会造成线程正在使用的资源(IO资源等)无法释放
现在我们采用interrupt(),相当于给线程打一个标记
我们看一下具体用法:

public class Demo {
    public static void main(String[] args) throws InterruptedException {
        //线程的中断
        Thread t1 = new Thread(new MyRunnable());
        t1.start();
        for(int i=0;i<5;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
            Thread.sleep(100);
        }
        t1.interrupt();
    }
}

class MyRunnable implements Runnable{
    @Override
    public void run() {
        for(int i=0;i<10;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                //e.printStackTrace();
                System.out.println("发现了中断标记,此线程自杀");
                return;
            }
        }
    }
}

控制台内容为:

main:0
Thread-0:0
Thread-0:1
main:1
Thread-0:2
main:2
main:3
Thread-0:3
main:4
Thread-0:4
Thread-0:5
发现了中断标记,此线程自杀

Process finished with exit code 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值