Java on the interruption of threads

/**
 * 方法中断线程(不推荐使用)
 * 
 * @author WanAkiko
 * 
 */
public class MethodInterrupt {

	public static void main(String[] args) {

		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				while (true) {
					// 不修改线程标识的前提下判断线程是否已被中断:boolean isInterrupted()
					if (Thread.currentThread().isInterrupted()) {
						System.out.println("提示:线程已被中断!");
						return;
					} else {
						System.out.println("提示:线程正在执行!");
					}
				}
			}
		};
		Thread thread = new Thread(runnable);
		thread.start(); // 开启线程
		try {
			Thread.sleep(3000); // 线程休眠3秒
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 中断线程并修改线程标识:void interrupt()
		thread.interrupt();
		System.out.println("提示:线程任务执行完毕!");
	}

}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44965393/article/details/112728271