前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >怎么查看线程的状态及interrupt优雅的关闭线程和interrupt()、interrupted()、isInterrupted()的作用以及区别在哪?

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

作者头像
向着百万年薪努力的小赵
发布2022-12-02 10:36:03
3170
发布2022-12-02 10:36:03
举报
文章被收录于专栏:小赵的Java学习小赵的Java学习

怎么查看线程状态

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

示例:

代码语言:javascript
复制
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

  1. 通过jstack 20376得到线程的状态信息
在这里插入图片描述
在这里插入图片描述

线程终止

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

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

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

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

代码语言:javascript
复制
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()示例如下:

代码语言:javascript
复制
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状态的定义:

代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-07-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 怎么查看线程状态
  • 线程终止
  • interrupt()、interrupted()、isInterrupted()的作用以及区别在哪?
  • 线程状态的定义
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档