当前位置:网站首页>線程-interrupt方法詳解
線程-interrupt方法詳解
2022-07-18 03:00:00 【白蝶丶】
我們如何在一個線程中暫停另一個線程的運行?
這裏不建議是使用stop方法,使用stop方法雖然可以强行終止正在運行或掛起的線程,但使用stop方法是很危險的。stop 方法會真正殺死線程,如果這時線程鎖住了共享資源,那麼當它被殺死後就再也沒有機會釋放鎖, 其它線程將永遠無法獲取鎖
我們可以使用interrupt方法。在使用該方式時,它並不會像stop方法那樣會中斷一個正在運行的線程,而是線程會繼續運行下去;但會設置該線程的中斷狀態,即設置為true,線程會不時地檢測這個中斷標示比特,以判斷線程是否應該被中斷(中斷狀態是否為true)
public class test2 {
public static void main(String[] args) {
try {
test2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void test2() throws InterruptedException {
Thread t2 = new Thread(()->{
while(true) {
Thread current = Thread.currentThread();
boolean interrupted = current.isInterrupted();
System.out.println(interrupted);
//自己來决定是否停止現場的運行
if(interrupted) {
System.out.println(interrupted);
break;
}
}
}, "t2");
t2.start();
//讓主線程睡眠一下
Thread.sleep(500);
t2.interrupt();
}
}
輸出結果:
但是當我們打斷阻塞中(sleep,wait,join)的線程會讓此線程產生一個InterruptedException异常,結束線程的運行。但如果該异常被線程捕獲住,該線程依然可以自行决定後續處理(終止運行,繼續運行,做一些善後工作等等),而且這個打斷阻塞中的線程是會重置標狀態為false;
@Slf4j
public class test1 {
public static void main(String[] args) throws InterruptedException {
TwoParseTermination twoParseTermination = new TwoParseTermination();
twoParseTermination.start();
Thread.sleep(3500);
twoParseTermination.stop();
}
}
@Slf4j
class TwoParseTermination {
private Thread monitor;
// 啟動線程
public void start() {
monitor = new Thread(() -> {
while (true) {
//拿到當前線程
Thread thread = Thread.currentThread();
if(thread.isInterrupted()) {
// 調用 isInterrupted拿到標記值 這個不會清除標記
System.out.println("料理後事 ...");
break; //終止線程
} else {
try {
Thread.sleep(1000);
System.out.println("執行監控的功能 ...");
} catch (InterruptedException e) {
System.out.println("設置打斷標記 ...");
//因為捕獲异常後標記值變成了false,這裏再打斷一下,就相當於把這個正在運行的線程給打斷了,所以這裏的標記值又變成了ture,如果這裏不重置這個標記值那麼這個線程是會一直運行的
thread.interrupt();
e.printStackTrace();
}
}
}
}, "monitor");
monitor.start();
}
// 終止線程
public void stop() {
monitor.interrupt();
}
}

關於isInterrupted()和Interrupted()方法
這兩個方法都可以判斷當前線程的打斷狀態,區別在於:
interrupted()是靜態方法,並且會重置當前線程的中斷狀態(還是false)。而isInterrupted()不會重置當前狀態
public class test2 {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(100 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
thread.interrupt();
Thread.currentThread().interrupt();
System.out.println("第一次"+Thread.interrupted());
System.out.println("第二次"+Thread.interrupted());
}
}
這裏我們interrupt了main線程,調用interrupted()方法就會重置為false
边栏推荐
- 第九十九期:flutter学习(二)
- Unit MySQL appears in MySQL Solution of service could not be found
- ESP8266 lua入门
- RobotFramework进阶(一)集成Pycharm及UI自动化用例编写
- Xpath实战之爬取学习猿地的猿著(上)
- 马斯克为何终止收购Twitter?
- 04 exit interrupt detection key
- 金融市场暴跌忍不住想抄底?劝你看完本文再做决定
- [design topics] project summary of graduation design topics based on C51 single chip microcomputer - 500 cases
- Send your code into space and develop 'the greatest work' with Huawei cloud
猜你喜欢

Unit MySQL appears in MySQL Solution of service could not be found

Alibaba cloud Internet of things platform construction

The end of kotlin plug-in and the rise of viewbinding

【MySQL】多表查询

Xpath实战之爬取学习猿地的猿著(下)

mysql中出现Unit mysql.service could not be found 的解决方法

"Open source star picking program" harbor high availability cluster design and deployment (practice + video), based on offline installation

RobotFramework进阶(三)集成Jenkins运行自动化用例

08 use timer to control LED flashing

Using PostgreSQL on PostgreSQL 15_ FDW performs parallel commit of transactions
随机推荐
Mqtt--- connect connection
"Open source star picking program" harbor high availability cluster design and deployment (practice + video), based on offline installation
A --- DMA serial port communication
Hcip notes (2)
阈值PSI代码
箭头函数与箭头函数的区别
Nacos as the registration and discovery center and configuration center of microservice architecture
两个CVE漏洞复现
10分钟带你进入Swagger的世界,快来看一看吧
Cache avalanche, cache breakdown, cache penetration
Shanghai port shipping AI container AI Unicorn gathers flying pupils, and the market share of port and shipping AI products is leading, driving the development of the whole industrial chain of port an
Recurrence of two CVE vulnerabilities
The difference between the elements dependencies and dependencymanagement
Wechat applet uni app can submit forms or log in. You need to check the consent agreement before you can proceed to the next step
基础概念
Xpath实战之爬取学习猿地的猿著(上)
爱可可AI前沿推介(7.15)
顺序表
08 use timer to control LED flashing
Configuration of teacher management module and MP automatic code generation