线程的几种状态及相互切换
摘自https://www.cnblogs.com/hejing-swust/p/8038263.html
阻塞
在wait和sleep方法调用的时候,会强制使用try-catch包住异常,这个是因为线程在执行的过程中受外部干预导致线程执行异常,需要开发者在程序中对中断做出相应的处理
@Test
public void test15() throws InterruptedException {
Thread t01=new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("线程执行出现中断");
}
}
});
t01.start();
Thread.sleep(100);
System.out.println("设置线程中断");
t01.interrupt();
while (Thread.activeCount()>2){}
System.out.println("run over");
}
和中断相关的几个方法
•Thread.interrupt(),设置当前中断标记为true(类似属性的set方法)
•Thread.isInterrupted(),检测当前的中断标记(类似属性的get方法)
•Thread.interrupted(),检测当前的中断标记,然后重置中断标记为false(类似属性的get方法+set方法)
使用案例-中断一个线程
@Test
public void test02() throws InterruptedException {
Thread t01 = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
if (Thread.interrupted()) {
throw new InterruptedException("执行过程中中断了当前线程");
} else {
System.out.println("1");
Thread.sleep(500);
}
}
} catch (Exception e) {
System.out.println("执行过程中中断了当前线程");
}
}
});
t01.start();
Thread.sleep(2000);
t01.interrupt();
while (Thread.activeCount() > 2) {
}
System.out.println("run over");
}
也可以用Thread.interrupted()+return的方法
2022-0318补充
可以通过如下命令查询进程内线程主动任务和被动任务切换的次数
pidstat -w -p 5121 1 100
参考:https://blog.csdn.net/ywk253100/article/details/29591755
https://maimai.cn/article/detail?fid=1424342759&efid=GOpd6L51RKJdvqMSQ5BFpw&use_rn=1