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

本文详细介绍了Java中线程的各种状态,包括如何查看线程状态、线程的生命周期及每种状态的特点。此外,还讲解了如何优雅地关闭线程以及interrupt()、interrupted()、isInterrupted()等方法的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

怎么查看线程状态

  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

向着百万年薪努力的小赵

感谢大佬,大佬步步高升

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值