JAVA-----如何优雅的关闭线程

仅提供学习,侵权必删,如有错误,敬请告知

一、定义全局变量

package Suo10;

public class Threadclose {
	private static volatile boolean zhuangtai = false;
	public static void qidong() {
		System.out.println(Thread.currentThread().getName()+"运行5秒后关闭!");
		while(!zhuangtai) {
			System.out.println(Thread.currentThread().getName()+"正在执行!");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public static void close() {
		zhuangtai = true;
		System.out.println("线程关闭!");
	}
	public static void main(String[] args) {
		Thread thread = new Thread("AA") {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				qidong();
			}
		};
		thread.start();
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("五秒已到了!");
		close();
	}
}

二、判断是否被打断

package Suo2;

public class Threadclose {
	public static void qidong() {
		System.out.println(Thread.currentThread().getName()+"运行五秒后关闭!");
		while(!Thread.currentThread().isInterrupted()){
			
		}
	}
	public static void main(String[] args) {
		Thread thread = new Thread(()-> {
			qidong();
		},"AA");
		thread.start();
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("五秒已到了!");
		thread.interrupt();
	}
}

三、停止(不推荐)

package Suo2;

public class Threadclose {
	public static void main(String[] args) {
		Thread thread = new Thread(()-> {
			while (true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()+"正在运行");
			}
		},"AA");
		thread.start();
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("五秒已到了!");
		thread.stop();
	}
}

发布了9 篇原创文章 · 获赞 2 · 访问量 130

猜你喜欢

转载自blog.csdn.net/fenghuaqingjun/article/details/104457080