多线程停止的几种方式(详细讲解)

方式一

使用退出标识,使得线程正常退出,即当run方法完成后进程终止。

public class TestFlagStop implements Runnable{

	//1、设置一个标示位
	private boolean flag = true;
	
	@Override
	public void run() {
		int i = 0;
		while(flag) {
			System.out.println("run...Thread"+i++);
		}
	}
	
	//2、设置一个公共的方法停止线程,转换标志位
	public void stop() {
		this.flag = false;
	}

	public static void main(String[] args) {
		TestFlagStop testStop = new TestFlagStop();
		new Thread(testStop).start();
		
		for (int i = 0; i < 1000; i++) {
			System.out.println("main"+i);
			if(i==900) {
				//调用stop方法切换标志位,让线程停止
				testStop.stop();
				System.out.println("线程该停止了");
			}
		}
	}
}

方式二

停止一个线程在之前老的JDK中使用的是Thread.stop()方法,但是后面发现这种处理方法是很危险而且不安全的,由于stop()方法已经在JDK中被标明是“作废/过期”的方法,显然它在功能上是具有缺陷的。这里直接遗弃掉即可。

方式二

使用interrupt方法中断线程。

首先我们用for-break配合interrupt方式停止线程:

public class InterruptBreakStop extends Thread {
	@Override
    public void run() {
        for (int i = 0; i < 500000; i++) {
            if (this.isInterrupted()) {
                System.out.println("已经是停止状态了!我要退出了!");
                break;
            }
            System.out.println("i=" + (i + 1));
        }
        System.out.println("我被输出,如果此代码是for又继续运行,线程并未停止!");
    }

    public static void main(String[] args) {
    	InterruptBreakStop thread = new InterruptBreakStop();
        thread.start();
        try {
            Thread.sleep(2000);
            thread.interrupt();
       
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

从这里可以发现,break只是跳出for循环,而for循环之后的代码照常会运行!
在这里插入图片描述
为了解决这种问题,可以采用return的方式终止线程。

public class InterruptReturnStop extends Thread {
	 @Override
	    public void run() {
	        while (true) {
	            if (this.isInterrupted()) {
	                System.out.println("停止了!");
	                return;
	            }
	            System.out.println("time=" + System.currentTimeMillis());
	        }
	    }

	    public static void main(String[] args) throws InterruptedException {
	    	InterruptReturnStop thread=new InterruptReturnStop();
	        thread.start();
	        thread.sleep(2000);
	        thread.interrupt();
	    }
}

输出结果:
在这里插入图片描述
一般推荐抛异常的方式,这样才能使得线程停止得以扩散。

public class InterruptExceptionStop extends Thread {
	@Override
    public void run() {
	 	try {
	 		while (true) {
	            if (this.isInterrupted()) {
	                System.out.println("停止了!");
	                throw new InterruptedException();
	            }
	            System.out.println("time=" + System.currentTimeMillis());
	        }
		} catch (InterruptedException e) {
			System.out.println( "抛异常了" );
			e.printStackTrace();
		}
    }

    public static void main(String[] args){
    	InterruptExceptionStop thread=new InterruptExceptionStop();
        thread.start();
        try {
			thread.sleep(2000);
			thread.interrupt();
		} catch (InterruptedException e) {
			System.out.println( "抛异常了呀" );
			e.printStackTrace();
		}
        
    }
}

在这里插入图片描述
注意:

如果在sleep状态下使用interrupt()停止某一线程,会进入catch语句,并且清除停止状态值,使之变为false。可以理解为互斥关系,一旦使用这个interrupt方法,就不能让线程进入休眠状态。否则就会报这个错误。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

怪 咖@

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

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

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

打赏作者

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

抵扣说明:

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

余额充值