Java代码中如何中断线程呢?

Java代码中如何中断线程呢?,第1张

下文笔者讲述使用Java代码中断线程的方法分享,如下所示:
实现思路:
    使用interrupt()方法进行线程中断
     在中断前,我们可使用isInterrupted()方法,判断一下线程是否已中断

package com.java265.other;
public class Test16 {
    /**
    * java265 示例程序
    */
	public static void main(String[] args) throws Exception {
		MyThread2 a = new MyThread2();
		// 启动线程
		a.start();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException x) {
		}
		System.out.println("in main() - 中断其他线程");
		a.interrupt();
		System.out.println("in main() - 离开");
	}
}

class MyThread2 extends Thread {
	public void run() {
		try {
			System.out.println("in run() - 将运行 work() 方法");
			work();
			System.out.println("in run() - 从 work() 方法回来");
		} catch (InterruptedException x) {
			System.out.println("in run() - 中断 work() 方法");
			return;
		}
		System.out.println("in run() - 休眠后执行");
		System.out.println("in run() - 正常离开");

	}

	public void work() throws InterruptedException {
	      while (true) {
	         if (Thread.currentThread().isInterrupted()) {
	            System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted());
	            Thread.sleep(2000);
	            System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted());
	         }
	      }
		}
}

-----运行以上代码,将输出以下信息-----
in run() - 将运行 work() 方法
in main() - 中断其他线程
in main() - 离开
C isInterrupted()=true
in run() - 中断 work() 方法

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/905684.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-15
下一篇2022-05-15

发表评论

登录后才能评论

评论列表(0条)

    保存