当前位置:网站首页>What common APIs are involved in thread state changes
What common APIs are involved in thread state changes
2022-06-25 07:24:00 【Bug trendsetter】
Basic thread mechanism
Executor
Manage the execution of multiple asynchronous tasks , Without programmers having to explicitly manage the life cycle of threads . Asynchrony here means that the execution of multiple tasks does not interfere with each other , No need to synchronize .
Daemon
Daemons are threads that provide services in the background when a program is running , Not an integral part of the program .
When all non - daemons end , And the program ends , It will kill all the daemons at the same time .
main() Belongs to non daemonic thread .
Use setDaemon() Method to set a thread as a guardian thread .
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.setDaemon(true);
}
sleep()
Thread.sleep(millisec) Method sleeps the currently executing thread ,millisec The unit is millisecond .
sleep() May throw InterruptedException, Because exceptions cannot be propagated back across threads main() in , So it has to be done locally . Other exceptions thrown in the thread also need to be handled locally .
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
yield()
For static methods Thread.yield() The call to declare that the current thread has completed the most important part of its life cycle , You can switch to other threads to execute . This method is just a suggestion for thread scheduler , It is only recommended that other threads with the same priority can run .
public void run() {
Thread.yield();
}
interrupt
A thread will automatically end after execution , If there is an exception in the running process, it will end ahead of time .
InterruptedException
By calling the interrupt() To interrupt the thread , If the thread is blocked 、 The state of waiting or waiting indefinitely , Then it will throw InterruptedException, So that the thread ends ahead of time . But it can't be interrupted I/O Blocking and synchronized The lock is blocked .
For the following code , stay main() Start a thread and interrupt it , Because the thread called Thread.sleep() Method , So a InterruptedException, So as to terminate the thread ahead of time , Do not execute subsequent statements .
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");
}
// result
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()
If a thread's run() Method to execute an infinite loop , And not implemented sleep() I'll throw it out later InterruptedException The operation of , Then call the thread's interrupt() Method does not allow the thread to end prematurely .
But the call interrupt() Method sets the thread's interrupt flag , Call at this time interrupted() Method will return true. So you can use interrupted() Method to determine whether the thread is in an interrupt state , So as to terminate the thread ahead of time .
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();
}
// result
Thread end
Executor Interrupt operation of
call Executor Of shutdown() Method will wait for the thread to finish executing before closing , But if you call shutdownNow() Method , It is equivalent to calling the interrupt() Method .
The following uses Lambda Create thread , Equivalent to creating an anonymous internal thread .
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");
}
// result
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)
If you just want to interrupt Executor One thread in , By using submit() Method to commit a thread , It will return one Future<?> object , By calling the cancel(true) Method to interrupt the thread .
Future<?> future = executorService.submit(() -> {
// ..
});
future.cancel(true);
Remember to point 「 Fabulous 」 and 「 Looking at 」↓
Love you
边栏推荐
- 14 bs对象.节点名称.name attrs string 获取节点名称 属性 内容
- [tool sharing] a software that pays equal attention to appearance and skills
- LabVIEW generate application (exe) and installer
- lotus v1.16.0-rc2 Calibration-net
- lotus v1.16.0-rc2 Calibration-net
- Chang Wei (variables and constants) is easy to understand
- 为什么要“除夕”,原来是内存爆了!
- keepalived監控進程,自動重啟服務進程
- 用动图讲解分布式 Raft
- 高数基础_函数的奇偶性
猜你喜欢
Why "New Year's Eve", the original memory burst!
【UVM入门 ===> Episode_9 】~ 寄存器模型、寄存器模型的集成、寄存器模型的常规方法、寄存器模型的应用场景
我们不一样
Escape analysis of 982 golang
Efficient exploration | an application practice of ES geographical location query
Debug through yalc before releasing NPM package
Harmony美食菜单界面
【一起上水硕系列】Day 5
Loopholes in the missed scanning system of Lvmeng and its repair scheme
TEMPEST HDMI泄漏接收 1
随机推荐
[Introduction aux uvm== > Episode 9] ~ modèle de registre, intégration du modèle de registre, méthode conventionnelle du modèle de registre, scénario d'application du modèle de registre
Enter an integer with any number of bits, and output the sum of each bit of the number. For example: 1234 – > 10
【UVM入門 ===> Episode_9 】~ 寄存器模型、寄存器模型的集成、寄存器模型的常規方法、寄存器模型的應用場景
Too beautiful promise because too young
关于硬件问题造成的MCU死机,过来人简单的谈一谈
Error reported during vivado simulation common 17-39
Google extender address
lotus v1.16.0-rc3 calibnet
太美的承诺因为太年轻
正版photoshop2022購買體驗經曆分享
lotus v1.16.0-rc2 Calibration-net
我的处女作杀青啦!
Shell命令学习
【一起上水硕系列】Day 4
14 bs对象.节点名称.name attrs string 获取节点名称 属性 内容
线程状态变化涉及哪些常用 API
TEMPEST HDMI泄漏接收 2
[2022 dark horse programmer] SQL optimization
Blue Bridge Cup SCM module code (timer) (code + comments)
Large funds support ecological construction, and Plato farm builds a real meta universe with Dao as its governance