线程终止的方法

学习心得

线程终止的3种方法:stop(),interrupt(),使用标志位

总结

1.stop()方法会直接杀死线程不论执行到哪里,破坏了线程的安全性,已停止使用

public class StopThread extends Thread{
    public int i=0;
    public int j=0;
    @Override
    public void run(){
        i++;
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        j++;
    }
    public static void main(String[] args) throws InterruptedException {
        StopThread stopThread = new StopThread();
        stopThread.start();
        Thread.sleep(1000);		//进入线程,执行i++
        stopThread.stop();    //立即打断线程
        //stopThread.interrupt();     //打断wait(),join(),sleep(),继续执行其他
        while (stopThread.isAlive()){

        }
        System.out.println(stopThread.i+"***"+stopThread.j);	//输出 1***0
    }
}

2.interrupt()方法会打断当前等待或阻塞状态使线程继续执行,直至线程结束。

public class StopThread extends Thread{
    public int i=0;
    public int j=0;
    @Override
    public void run(){
        i++;
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        j++;
    }
    public static void main(String[] args) throws InterruptedException {
        StopThread stopThread = new StopThread();
        stopThread.start();
        Thread.sleep(1000);		//进入线程,执行i++
        //stopThread.stop();    //立即打断线程
        stopThread.interrupt();     //打断wait(),join(),sleep(),继续执行其他
        while (stopThread.isAlive()){

        }
        System.out.println(stopThread.i+"***"+stopThread.j);	//输出 1***1,并抛出异常。
    }
}

3.增加标志位方法,标志位需使用voliate关键字修饰,保证多线程之间的可见性。

public class StopThread extends Thread{
    public int i=0;
    public int j=0;
    public static voliate boolean falg = true;	//volicate保证多线程可见性
    @Override
    public void run(){
        while(flag){
            i++;
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            j++;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        StopThread stopThread = new StopThread();
        stopThread.start();
        Thread.sleep(1000);		//进入线程,执行i++
        stopThread.falg = false;
        while (stopThread.isAlive()){

        }
        System.out.println(stopThread.i+"***"+stopThread.j);	//输出 1***1
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值