怎么查看线程的状态及interrupt优雅的关闭线程和interrupt()、interrupted()、isInterrupted()的作用以及区别在哪?

怎么查看线程的状态及interrupt优雅的关闭线程和interrupt()、interrupted()、isInterrupted()的作用以及区别在哪?示例:查看状态:刚才我们讲过,一个线程里面任务正常执行完毕,状态就是TERMINATED,就是终止状态。但是,如果我线程里面的任务一直没有执行完成,我想去终止这个线程,或者我给点信息给到线程里,告诉线程我想终止结束呢!所以我可以强制去关闭线程:线程提供一个stop方法,该方法不建议使用,已经过时了!!因为stop是强行关闭线程,线程里面的任务都不在执行,不管线程的任务是否执行成功与否,就算执行到一半也会强制关闭!导致很多不可控制的结果,比如支付付一半等等!!所以我们要需要去优雅的关闭。什么叫做优雅关

怎么查看线程状态

  1. jps指令查看我当前的进程ID
  2. jstack 线程ID

示例:

public class StatusDemo { 
   
	public static void main(String[] args) { 
   
		new Thread(()->{ 
   
			while(true) { 
   
				LockSupport.park();
			}
		},"huihui_waiting").start(); //阻塞状态
		new Thread(()->{ 
   
			try { 
   
				Thread.sleep(100000);
			} catch (InterruptedException e){ 
   
				e.printStackTrace();
			}
		},"huihui_time_waiting").start(); //阻塞状态
	new Thread(new BlockClass(),"huihui_thread").start();
	new Thread(new BlockClass(),"huihui_block").start();
	}
	static class BlockClass extends Thread{ 
   
		public void run(){ 
   
			synchronized(BlockClass.class){ 
   
				try{ 
   
					Thread.sleep(1000000);
					} catch (InterruptedException e) { 
   
						e.printStackTrace();
					}
			}
		}
	}
}

查看状态:

  1. jps指令得到我程序的进程信息
    在这里插入图片描述
    得到我当前的进程为20376
  2. 通过jstack 20376得到线程的状态信息
    在这里插入图片描述

线程终止

刚才我们讲过,一个线程里面任务正常执行完毕,状态就是TERMINATED,就是终止状态。
但是,如果我线程里面的任务一直没有执行完成,我想去终止这个线程,或者我给点信息给到线程里,告诉线程我想终止结束呢!
所以我可以强制去关闭线程:线程提供一个stop方法,该方法不建议使用,已经过时了!!

因为stop是强行关闭线程,线程里面的任务都不在执行,不管线程的任务是否执行成功与否,就算执行到一半也会强制关闭!导致很多不可控制的
结果,比如支付付一半等等!!

所以我们要需要去优雅的关闭。什么叫做优雅关闭,就是我告诉你,我需要关闭了,但是我不强制关闭

线程里面提供了interrupt来优雅关闭,示例如下

package thread.demo.interrupt;
public class InterruptTest implements Runnable{ 
   
	@Override
	public void run() { 
   
		while (!Thread.currentThread().isInterrupted()) { 
   
		//false
			try { 
   
				Thread.sleep(100);
				} catch (InterruptedException e) { 
   
					e.printStackTrace();
					System.out.println("异常里的isInterrupted:"+Thread.currentThread().isInterrupted());
					Thread.currentThread().interrupt(); //再次中断
					System.out.println("再次中断:"+Thread.currentThread().isInterrupted());
				}
			}
		System.out.println("线程结束");
	}
	public static void main(String[] args) throws InterruptedException { 
   
		Thread t1=new Thread(new InterruptTest());
		t1.start();
		Thread.sleep(1000);
		//不中断,线程不进异常不中断,中断,线程会进入异常并且复位
		t1.interrupt();
	}
}

其思想:有个共享变量 类型boolean的isInterrupted,默认是false,然后外面可以改成true,线程里面可以获取到状态,如果是true,那么就说明外面有人想要我中断,那么如果我当前是waiting或者timewaiting状态,就会唤醒我的线程进入InterruptedException异常!!

interrupt()、interrupted()、isInterrupted()的作用以及区别在哪?

  • interrupt() 优雅的通知线程需要结束,如果线程在waiting 会抛出InterruptedException,线程自己决定要不要结束,异常会触发复位

  • isInterrupted()获取线程的中断标记,但是不会进行复位操作

  • interrupted()获取线程的中断标记,并且主动执行复位操作

interrupted()示例如下:

public static void main(String[] args) throws InterruptedException { 
   
	Thread.currentThread().interrupt();
	System.out.println(Thread.interrupted()); //返回true,当前线程被interrupt
	System.out.println(Thread.currentThread().isInterrupted()); //获取线程的interrupt状态,本来应该是true,但是interrupted触发了复位,为false
}

线程状态的定义

其实Thread类下有JAVA层面对Thread状态的定义:

public enum State { 
   
	/** * Thread state for a thread which has not yet started. */
	NEW,
	/** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */
	RUNNABLE,
	/** * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling *{@link Object#wait() Object.wait}. */
	BLOCKED,
	/** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link Object#wait() Object.wait} with no timeout</li> * <li>{@link #join() Thread.join} with no timeout</li> *<li>{@link LockSupport#park() LockSupport.park}</li> * </ul> * * <p>A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called <tt>Object.wait()</tt> * on an object is waiting for another thread to call * <tt>Object.notify()</tt> or <tt>Object.notifyAll() </tt> on * that object. A thread that has called <tt>Thread.join()</tt> * is waiting for a specified thread to terminate. */
	WAITING,
	/** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: * <ul> * <li>{@link #sleep Thread.sleep}</li> * <li>{@link Object#wait(long) Object.wait} with timeout</li> *<li>{@link #join(long) Thread.join} with timeout</li> *<li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> *<li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> * </ul> */
	TIMED_WAITING,
	/** * Thread state for a terminated thread. * The thread has completed execution. */
	TERMINATED;
}

其实我们想一下,任何东西的生命周期都是开始与死亡!!
所以线程肯定有2种状态
初始(NEW)
新创建了一个线程对象,但是没有调用start()方法
终止(TERMINATED)
这个线程执行完毕
除了这2种状态外,线程还有以下几种状态
运行(RUNNABLE)
我们线程开启是需要start 的,所以初始化后,有个运行状态
等待(WAITING)
进入该状态的线程需要等待其他线程做出一些特定动作,线程进入了这个状态一般调用了

  • Object.wait() 需要等待另一个线程执行Object.notify()或者Object.notifyAll()
  • Thread.join() 需要等待线程执行完成
  • jpsLockSupport.park() 等待执行LockSupport.unpark(thread)

超时等待(TIMED_WAITING)
指定了时间后自行返回,等待一段时间后,会唤醒线程,而不是永久等待,一般执行过

  • Thread.sleep(long)
  • Object.wait(long)
  • Thread.join(long)
  • LockSupport.parkNanos()
  • LockSupport.parkUntil()

阻塞(BLOCKED)
线程阻塞于锁,比如synchronized

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/210040.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • datagrip永久激活(JetBrains全家桶)

    (datagrip永久激活)JetBrains旗下有多款编译器工具(如:IntelliJ、WebStorm、PyCharm等)在各编程领域几乎都占据了垄断地位。建立在开源IntelliJ平台之上,过去15年以来,JetBrains一直在不断发展和完善这个平台。这个平台可以针对您的开发工作流进行微调并且能够提供…

    2022年3月31日
  • 大数据:数据采集平台之Scribe[通俗易懂]

    大数据:数据采集平台之Scribe[通俗易懂]大数据:数据采集平台之ScribeGitHub地址:https://github.com/facebookarchive/scribeScribe是Facebook开发的数据(日志)收集系统。已经多年不维护。部署架构如下:参考:https://mp.weixin.qq.com/s/emQ_94T0_Hw3ywQc0-4Dtg…

    2022年5月18日
  • C++标准输入输出流_seekg函数详解

    C++标准输入输出流_seekg函数详解对文件输入输出流的操作函数主要有1/seekg()和tellg() //对输入流的操作(也就是读)2/seekp()和tellp() //对输出流的操作(也就是写) 1.seekg()是对输入文件定位,它有两个参数:第一个参数是偏移量,第二个参数是基地址。对于第一个参数,可以是正负数值,正的表示向后偏移,负的表示向前偏移。而第二个参数可以是:   ios::beg

    2022年5月24日
  • WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping。「建议收藏」

    WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping。「建议收藏」WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping。

    2022年4月24日
  • 矩阵等价-相似-合同

    矩阵等价-相似-合同1.矩阵等价2.矩阵相似3.矩阵合同矩阵等价定义如果矩阵A经过有限次初等行变换变成矩阵B,就成矩阵A与B行等价。如果矩阵A经过有限次初等列变换变成矩阵B,就成矩阵A与B列等价。如果矩阵A经过有限次初等变换变成矩阵B,就称矩阵A与B等价。性质反身性:A~A对称性:若AB,则BA传递性:若AB,BC,则A~C推论:有两个m×n阶矩阵A和B,如果这两个矩阵满足B=QAP(P是n×n阶可逆矩阵,Q是m×m阶可逆矩阵),那么这两个矩阵之间是等价关系。r(A)=r(B),且A与B为同型矩阵。

    2022年10月29日
  • 细数人们对安卓的误解

    误解一:安卓是iOS的后辈不知不觉,安卓已经成为了世界上最流行的移动智能系统,就市场占有率来看,安卓甚至要高于引领了智能机和平板电脑革命的iOS。安卓的红火深远地影响了IT行业,全球最大的社交网络F

    2021年12月27日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号