[Java] java 强制中断线程运行 →→→→→进入此内容的聊天室

来自 , 2021-02-27, 写在 Java, 查看 107 次.
URL http://www.code666.cn/view/55a7cf9c
  1. public class Test implements Runnable {
  2.         public void run() {
  3.                 try {
  4.                         System.out.println("在run()方法中 - 这个线程会运行20秒");
  5.                         Thread.sleep(20000);
  6.                         System.out.println("在run()方法中 - 继续运行");
  7.                 } catch (InterruptedException x) {
  8.                         System.out.println("在run()方法中 - 中断线程"); // 捕捉到中断异常,立即停止运行
  9.                         return;
  10.                 }
  11.                 System.out.println("在run()方法中 - 休眠之后继续完成");
  12.                 System.out.println("在run()方法中 - 正常退出");
  13.         }
  14.  
  15.         public static void main(String[] args) {
  16.                 Test si = new Test();
  17.                 Thread t = new Thread(si);
  18.                 t.start();
  19.                 // 在此休眠是为确保线程能运行一会
  20.                 try {
  21.                         Thread.sleep(2000);
  22.                 } catch (InterruptedException x) {
  23.                 }
  24.                 System.out.println("在main()方法中 - 中断其它线程");
  25.                 t.interrupt(); // 实际上t线程要运行20秒,但是在主线程中2秒后就终止了t线程
  26.                 System.out.println("在main()方法中 - 退出");
  27.         }
  28. }
  29.  

回复 "java 强制中断线程运行"

这儿你可以回复上面这条便签

captcha