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

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

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

怎么查看线程状态

  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();
					}
			}
		}
	}
}

Jetbrains全家桶1年46,售后保障稳定

查看状态:

  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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • idea2021永久激活注册码-激活码分享

    (idea2021永久激活注册码)最近有小伙伴私信我,问我这边有没有免费的intellijIdea的激活码,然后我将全栈君台教程分享给他了。激活成功之后他一直表示感谢,哈哈~IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html…

    2022年3月28日
    515
  • matlab循环读取txt文件「建议收藏」

    matlab循环读取txt文件「建议收藏」一般情况下,假如我要读取一个名为a.txt的文件,只需要利用下面的语句:a=load(‘a.txt’);现在假如我需要循环读取saif_1.txt,saif_2.txt,,,一直到saif_10.txt,他们都是10*1的矩阵,对他们进行转置操作后,再合并到一个文件中,可以利用下面的语句:forN=1:10a=load([‘saif_’,num2str(N),’.txt’]);……

    2022年10月7日
    0
  • B站上适合程序员的学习资源【赶紧收藏!】

    B站上适合程序员的学习资源【赶紧收藏!】

    2022年2月11日
    37
  • stuffing list_difflib

    stuffing list_difflibhttps://blog.csdn.net/heimu24/article/details/535813621.2创建图片列表清单这一步我们需要创建自己图片数据集的清单txt文件,这里提供两种方法。方法1:创建一个sh文件cd~/caffe-master/sudogeditexamples/images/create_filelist.shsudo就是获取管理员权限,gedit…

    2022年9月29日
    0
  • 特色网站收集(332个)「建议收藏」

    特色网站收集(332个)「建议收藏」1.del.icio.ushttp://del.icio.us/在线收藏夹.域名很有创意.影响也很广.支持从浏览器导出和导出到浏览器.2.Anonymousehttp://anonymouse.org

    2022年7月3日
    38
  • ADB-安装配置[通俗易懂]

    ADB-安装配置[通俗易懂]一、只要下载ADB安装包即可就这4个文件:备注:如果下载放入到D盘去解压,打开dos窗口那么就要进入到D盘,然后再去执行adb命令,输入adb查看它是否安装成功二、ADB命令简单使用查看连接设

    2022年8月4日
    3

发表回复

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

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