当前位置:网站首页>线程状态变化涉及哪些常用 API
线程状态变化涉及哪些常用 API
2022-06-25 06:38:00 【BUG弄潮儿】
基础线程机制
Executor
管理多个异步任务的执行,而无需程序员显式地管理线程的生命周期。这里的异步是指多个任务的执行互不干扰,不需要进行同步操作。

Daemon
守护线程是程序运行时在后台提供服务的线程,不属于程序中不可或缺的部分。
当所有非守护线程结束时,程序也就终止,同时会杀死所有守护线程。
main() 属于非守护线程。
使用 setDaemon() 方法将一个线程设置为守护线程。
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.setDaemon(true);
}sleep()
Thread.sleep(millisec) 方法会休眠当前正在执行的线程,millisec 单位为毫秒。
sleep() 可能会抛出 InterruptedException,因为异常不能跨线程传播回 main() 中,因此必须在本地进行处理。线程中抛出的其它异常也同样需要在本地进行处理。
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}yield()
对静态方法 Thread.yield() 的调用声明了当前线程已经完成了生命周期中最重要的部分,可以切换给其它线程来执行。该方法只是对线程调度器的一个建议,而且也只是建议具有相同优先级的其它线程可以运行。
public void run() {
Thread.yield();
}中断
一个线程执行完毕之后会自动结束,如果在运行过程中发生异常也会提前结束。
InterruptedException
通过调用一个线程的 interrupt() 来中断该线程,如果该线程处于阻塞、限期等待或者无限期等待状态,那么就会抛出 InterruptedException,从而提前结束该线程。但是不能中断 I/O 阻塞和 synchronized 锁阻塞。
对于以下代码,在 main() 中启动一个线程之后再中断它,由于线程中调用了 Thread.sleep() 方法,因此会抛出一个 InterruptedException,从而提前结束线程,不执行之后的语句。
public class InterruptExample {
private static class MyThread1 extends Thread {
@Override
public void run() {
try{
Thread.sleep(2000);
System.out.println("Thread run");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new MyThread1();
thread1.start();
thread1.interrupt();
System.out.println("Main run");
}
//结果
Main run
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at InterruptExample.lambda$main$0(InterruptExample.java:5)
at InterruptExample$$Lambda$1/713338599.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)interrupted()
如果一个线程的 run() 方法执行一个无限循环,并且没有执行 sleep() 等会抛出 InterruptedException 的操作,那么调用线程的 interrupt() 方法就无法使线程提前结束。
但是调用 interrupt() 方法会设置线程的中断标记,此时调用 interrupted() 方法会返回 true。因此可以在循环体中使用 interrupted() 方法来判断线程是否处于中断状态,从而提前结束线程。
public class InterruptExample {
private static class MyThread2 extends Thread {
@Override
public void run() {
while (!interrupted()) {
// ..
}
System.out.println("Thread end");
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread2 = new MyThread2();
thread2.start();
thread2.interrupt();
}
//结果
Thread endExecutor 的中断操作
调用 Executor 的 shutdown() 方法会等待线程都执行完毕之后再关闭,但是如果调用的是 shutdownNow() 方法,则相当于调用每个线程的 interrupt() 方法。
以下使用 Lambda 创建线程,相当于创建了一个匿名内部线程。
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> {
try {
Thread.sleep(2000);
System.out.println("Thread run");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executorService.shutdownNow();
System.out.println("Main run");
}
//结果
Main run
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at ExecutorInterruptExample.lambda$main$0(ExecutorInterruptExample.java:9)
at ExecutorInterruptExample$$Lambda$1/1160460865.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)如果只想中断 Executor 中的一个线程,可以通过使用 submit() 方法来提交一个线程,它会返回一个 Future<?> 对象,通过调用该对象的 cancel(true) 方法就可以中断线程。
Future<?> future = executorService.submit(() -> {
// ..
});
future.cancel(true);记得点「赞」和「在看」↓
爱你们
边栏推荐
- joda. Time get date summary
- Fastadmin cascade clear data
- Error reported during vivado simulation common 17-39
- SQL query, if value is null then return 1 - SQL query, if value is null then return 1
- lotus windowPoSt 手动触发时空证明计算
- Blue Bridge Cup SCM module code (matrix key) (code + comments)
- Flexbox on ie11: stretching images for no reason- Flexbox on IE11: image stretched for no reason?
- Change the current count of auto increment values in MySQL- Changing the current count of an Auto Increment value in MySQL?
- 【xxl-job】池塘水绿风微暖,记得玉真初见面
- Blue Bridge Cup SCM module code (external interrupt) (code + comment)
猜你喜欢

Simple and complete steps of vivado project
![[Shangshui Shuo series] day 5](/img/83/28834addd8198d4bcdc718eccf5754.png)
[Shangshui Shuo series] day 5

Pratique de gestion hiérarchique basée sur kubesphere

从感知机到Transformer,一文概述深度学习简史

【他字字不提爱,却句句都是爱】

Practice of hierarchical management based on kubesphere

MCU IO explanation (pull-up pull-down quasi bidirectional input / output push-pull open drain)

Make enough money to go back home

Several schemes of traffic exposure in kubernetes cluster

Enter an integer with any number of bits, and output the sum of each bit of the number. For example: 1234 – > 10
随机推荐
Fastadmin cascade clear data
Shandong finds clean energy that can be used by China for 3800 years? You should know the truth first
Finally, when you open source the applet ~
[2022 dark horse programmer] SQL optimization
Kubernetes 集群中流量暴露的几种方案
MCU IO explanation (pull-up pull-down quasi bidirectional input / output push-pull open drain)
[tool sharing] a software that pays equal attention to appearance and skills
Operate cnblogs metaweblog API
StreamNative Platform 1.5 版本发布,集成 Istio、支持 OpenShift 部署
Conditional grouping with $exists inside $cond
joda. Time get date summary
【UVM入门 ===> Episode_9 】~ 寄存器模型、寄存器模型的集成、寄存器模型的常规方法、寄存器模型的应用场景
I have used it for six years!
Solar orbiter captured the full picture of the largest prominence eruption in history
我与CSDN的一年时光及大学经验分享
How do I know if mysqlnd is an active driver- How to know if MySQLnd is the active driver?
lotus windowPoSt 手动触发时空证明计算
Blue Bridge Cup SCM module code (matrix key) (code + comments)
Blue Bridge Cup SCM module code (external interrupt) (code + comment)
Blue Bridge Cup SCM module code (LED) (code + comments)