终结者:终止线程循环的方式

        迫于需求,有时候我们需要在一个线程中写上一个死循环,那么问题来了:当线程启动开始运行时,我们如何有效的结束该死循环,这里给大家总结如下几种方式:

        方式一:线程中循环条件为线程全局变量

文件1:

public class TestThread extends Thread{
	
	boolean isStop = true;
	
	public void stopThread(){
		isStop = false;
	}
	
	@Override
	public void run() {
		while(isStop){
			System.out.println("线程正在运行...");
		}
		System.err.println("线程已停止运行...");
	}
}

文件2:

public class Test {
	
	public static void main(String[] args) throws InterruptedException {
		TestThread thread = new TestThread();
		thread.start();
		Thread.sleep(2000);
		thread.stopThread();
	}
}

        方式二:线程中循环条件使用isInterrupted方法

文件1:

public class TestThread extends Thread {

    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("线程正在运行...");
        }
        System.err.println("线程已停止运行...");
    }
}

文件2:

public class Test{
    public static void main(String args[]) throws Exception {
    	TestThread thread = new TestThread();
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();// 发出中断请求
    }
}

        方式三:在循环体中写一行出现异常的代码(不可取)

文件1:

public class TestThread extends Thread {

	@Override
	public void run() {
		try {
			while (true) {
				System.out.println("线程正在运行...");
				Thread.sleep(1000);//不能缺少
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.err.println("线程已停止运行...");
	}
}

文件2:

public class Test {

	public static void main(String[] args) throws InterruptedException {
		TestThread thread = new TestThread();
		thread.start();
		Thread.sleep(2000);
		thread.interrupt();
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序猿老高

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

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

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

打赏作者

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

抵扣说明:

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

余额充值