停止线程的两种方式(异常和Return)

本文介绍了两种在Java中处理线程中断的方式:一种是通过抛出异常来响应中断请求并终止线程;另一种是在线程运行过程中检查中断状态,如被设置则提前结束线程。这两种方式各有优缺点,在实际应用中可以根据具体需求选择合适的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package ExceptionBreak2;

public class TestMain {

	public static void main(String[] args) throws InterruptedException {
		MyThread mt = new MyThread();
		mt.start();
		
		Thread.sleep(200);
		mt.interrupt();

	}
}



package ExceptionBreak2;

public class MyThread extends Thread {
	private int count;

	public void run() {

		try {
			for (int i = 0; i < 100000; i++) {
				System.out.println(this.isInterrupted());
				System.out.println(i);
				if (this.isInterrupted()) { // 若 为 中断状态则break
					System.out.println(i);
					System.out.println("end");
					throw new Exception();
				}

			}
			System.out.println("over");
		} catch (Exception e) {
			System.out.println("log");
		}
	}

}



2:RETURN  但是一般来说是建议使用异常的方法进行线程的停止 这样 线程会得以向上传播 

package ReturnMethodStopThread;

public class TestMain {

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




package ReturnMethodStopThread;

public class MyThread extends Thread {

	public void run() {
		while (1 == 1) {
			if (this.interrupted()) {
				System.out.println("OVER");
				return;
			}
			System.out.println("Test");
		}

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值