如何结束线程-线程中断

停止现成的方式

线程停止的方式:

  • 线程执行完毕,自然会停止
  • 异常退出
  • 设置了标志位,当标志位为false时退出
  • 线程中断退出
    (这也是一道常见面试题)

线程函数执行完毕正常退出和发生异常被迫退出都不受我们控制,下面讨论控制线程停止的方式。

设置退出标志位

package com.sync.demo;

import javax.swing.text.html.HTML.Tag;

public class Demo5 {

	public static void main(String[] args) {
		ThreadC c = new ThreadC();
		Thread thread = new Thread(c);
		thread.start();
		try {
			Thread.sleep(3000);
			c.setTag(false);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
	static class ThreadC implements Runnable{
		
		private boolean Tag = true;
		
		
		public boolean isTag() {
			return Tag;
		}

		public void setTag(boolean tag) {
			Tag = tag;
		}

		public ThreadC() {
			super();
		}

		@Override
		public void run() {
			while (true) {
				if (!Tag) {
					System.out.println("=========退出============");
					return ;
				}else {
					System.out.println("=========run============");
				}	
			}
		}
	}

}

线程中断

java提供了线程中断机制,可以利用线程中断机制来结束线程,运行过程中检查线程是否被中断或者捕获InterruptedException异常。
判断中断的两种方式:
Thread.interrupted(); 可以设置中断的值为false
isInterrupted()

检查中断:

public class Demo5 {

	public static void main(String[] args) {
		ThreadD threadD = new ThreadD();
		threadD.start();
		try {
			Thread.sleep(3000);
			threadD.interrupt();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
	static class ThreadD extends Thread{

		public ThreadD() {
			super();
		}

		@Override
		public void run() {
			while (true) {
				if (isInterrupted()) {
					System.out.println("=========退出============");
					return ;
				}else {
					System.out.println("=========run============");
				}	
			}
		}
	}
	}

利用捕获中断停止线程:

public class Demo5 {

	public static void main(String[] args) {
		ThreadE threadE = new ThreadE();
		threadE.start();
		try {
			Thread.sleep(3000);
			threadE.interrupt();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	static class ThreadE extends Thread {

		public ThreadE() {
			super();
		}

		@Override
		public void run() {
			try {
				test1();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		private void test1() throws InterruptedException {
			while (true) {
				if (!isInterrupted()) {
					System.out.println("=========run============");
				} else {
					throw new InterruptedException();
				}
			}

		}

	}
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值