加入收藏 | 设为首页 | 会员中心 | 我要投稿 葫芦岛站长网 (https://www.0429zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

带你聊聊 Java 并发编程之线程基础

发布时间:2019-11-08 05:53:35 所属栏目:优化 来源:小九
导读:【线下技术沙龙】11月23日,多云时代开启企业业务新高度,安全如何与时俱进? 01、简介 百丈高楼平地起,要想学好多线程,首先还是的了解一下线程的基础,这边文章将带着大家来了解一下线程的基础知识。 02、线程的创建方式 实现 Runnable 接口 继承 Thread

线程运行状态时 Thread.isInterrupted() 返回的线程状态是 false,然后调用 thread.interrupt() 中断线程 Thread.isInterrupted() 返回的线程状态是 true,最后调用 Thread.interrupted() 复位线程Thread.isInterrupted() 返回的线程状态是 false 或者抛出 InterruptedException 异常之前,线程会将状态设为 false。

下面来看下两种方式复位线程的代码,首先是 Thread.interrupted() 的方式复位代码:

  1. public class InterruptDemo { 
  2.  
  3.     public static void main(String[] args) throws InterruptedException { 
  4.         Thread thread = new Thread(() -> { 
  5.             while (true) { 
  6.                 //Thread.currentThread().isInterrupted()默认是false,当main方式执行thread.interrupt()时,状态改为true 
  7.                 if (Thread.currentThread().isInterrupted()) { 
  8.                     System.out.println("before:" + Thread.currentThread().isInterrupted());//before:true 
  9.                     Thread.interrupted(); // 对线程进行复位,由 true 变成 false 
  10.                     System.out.println("after:" + Thread.currentThread().isInterrupted());//after:false 
  11.                 } 
  12.             } 
  13.         }, "interruptDemo"); 
  14.         thread.start(); 
  15.         TimeUnit.SECONDS.sleep(1); 
  16.         thread.interrupt(); 
  17.     } 

抛出 InterruptedException 复位线程代码:

  1. public class InterruptedExceptionDemo { 
  2.  
  3.     public static void main(String[] args) throws InterruptedException { 
  4.         Thread thread = new Thread(() -> { 
  5.             while (!Thread.currentThread().isInterrupted()) { 
  6.                 try { 
  7.                     TimeUnit.SECONDS.sleep(1); 
  8.                 } catch (InterruptedException e) { 
  9.                     e.printStackTrace(); 
  10.                     // break; 
  11.                 } 
  12.             } 
  13.         }, "interruptDemo"); 
  14.         thread.start(); 
  15.         TimeUnit.SECONDS.sleep(1); 
  16.         thread.interrupt(); 
  17.         System.out.println(thread.isInterrupted()); 
  18.     } 

(编辑:葫芦岛站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!