Java 并發(fā)編程之線程掛起、恢復(fù)與終止
掛起和恢復(fù)線程
Thread 的API中包含兩個(gè)被淘汰的方法,它們用于臨時(shí)掛起和重啟某個(gè)線程,這些方法已經(jīng)被淘汰,因?yàn)樗鼈兪遣话踩?,不穩(wěn)定的。如果在不合適的時(shí)候掛起線程(比如,鎖定共享資源時(shí)),此時(shí)便可能會(huì)發(fā)生死鎖條件——其他線程在等待該線程釋放鎖,但該線程卻被掛起了,便會(huì)發(fā)生死鎖。另外,在長(zhǎng)時(shí)間計(jì)算期間掛起線程也可能導(dǎo)致問(wèn)題。
下面的代碼演示了通過(guò)休眠來(lái)延緩運(yùn)行,模擬長(zhǎng)時(shí)間運(yùn)行的情況,使線程更可能在不適當(dāng)?shù)臅r(shí)候被掛起:
public class DeprecatedSuspendResume extends Object implements Runnable{
//volatile關(guān)鍵字,表示該變量可能在被一個(gè)線程使用的同時(shí),被另一個(gè)線程修改
private volatile int firstVal;
private volatile int secondVal;
//判斷二者是否相等
public boolean areValuesEqual(){
return ( firstVal == secondVal);
}
public void run() {
try{
firstVal = 0;
secondVal = 0;
workMethod();
}catch(InterruptedException x){
System.out.println("interrupted while in workMethod()");
}
}
private void workMethod() throws InterruptedException {
int val = 1;
while (true){
stepOne(val);
stepTwo(val);
val++;
Thread.sleep(200); //再次循環(huán)錢(qián)休眠200毫秒
}
}
//賦值后,休眠300毫秒,從而使線程有機(jī)會(huì)在stepOne操作和stepTwo操作之間被掛起
private void stepOne(int newVal) throws InterruptedException{
firstVal = newVal;
Thread.sleep(300); //模擬長(zhǎng)時(shí)間運(yùn)行的情況
}
private void stepTwo(int newVal){
secondVal = newVal;
}
public static void main(String[] args){
DeprecatedSuspendResume dsr = new DeprecatedSuspendResume();
Thread t = new Thread(dsr);
t.start();
//休眠1秒,讓其他線程有機(jī)會(huì)獲得執(zhí)行
try {
Thread.sleep(1000);}
catch(InterruptedException x){}
for (int i = 0; i < 10; i++){
//掛起線程
t.suspend();
System.out.println("dsr.areValuesEqual()=" + dsr.areValuesEqual());
//恢復(fù)線程
t.resume();
try{
//線程隨機(jī)休眠0~2秒
Thread.sleep((long)(Math.random()*2000.0));
}catch(InterruptedException x){
//略
}
}
System.exit(0); //中斷應(yīng)用程序
}
}
某次運(yùn)行結(jié)果如下:

從areValuesEqual()返回的值有時(shí)為true,有時(shí)為false。以上代碼中,在設(shè)置firstVal之后,但在設(shè)置secondVal之前,掛起新線程會(huì)產(chǎn)生麻煩,此時(shí)輸出的結(jié)果會(huì)為false(情況1),這段時(shí)間不適宜掛起線程,但因?yàn)榫€程不能控制何時(shí)調(diào)用它的suspend方法,所以這種情況是不可避免的。
當(dāng)然,即使線程不被掛起(注釋掉掛起和恢復(fù)線程的兩行代碼),如果在main線程中執(zhí)行asr.areValuesEqual()進(jìn)行比較時(shí),恰逢stepOne操作執(zhí)行完,而stepTwo操作還沒(méi)執(zhí)行,那么得到的結(jié)果同樣可能是false(情況2)。
下面我們給出不用上述兩個(gè)方法來(lái)實(shí)現(xiàn)線程掛起和恢復(fù)的策略——設(shè)置標(biāo)志位。通過(guò)該方法實(shí)現(xiàn)線程的掛起和恢復(fù)有一個(gè)很好的地方,就是可以在線程的指定位置實(shí)現(xiàn)線程的掛起和恢復(fù),而不用擔(dān)心其不確定性。
對(duì)于上述代碼的改進(jìn)代碼如下:
public class AlternateSuspendResume extends Object implements Runnable {
private volatile int firstVal;
private volatile int secondVal;
//增加標(biāo)志位,用來(lái)實(shí)現(xiàn)線程的掛起和恢復(fù)
private volatile boolean suspended;
public boolean areValuesEqual() {
return ( firstVal == secondVal );
}
public void run() {
try {
suspended = false;
firstVal = 0;
secondVal = 0;
workMethod();
} catch ( InterruptedException x ) {
System.out.println("interrupted while in workMethod()");
}
}
private void workMethod() throws InterruptedException {
int val = 1;
while ( true ) {
//僅當(dāng)賢臣掛起時(shí),才運(yùn)行這行代碼
waitWhileSuspended();
stepOne(val);
stepTwo(val);
val++;
//僅當(dāng)線程掛起時(shí),才運(yùn)行這行代碼
waitWhileSuspended();
Thread.sleep(200);
}
}
private void stepOne(int newVal)
throws InterruptedException {
firstVal = newVal;
Thread.sleep(300);
}
private void stepTwo(int newVal) {
secondVal = newVal;
}
public void suspendRequest() {
suspended = true;
}
public void resumeRequest() {
suspended = false;
}
private void waitWhileSuspended()
throws InterruptedException {
//這是一個(gè)“繁忙等待”技術(shù)的示例。
//它是非等待條件改變的最佳途徑,因?yàn)樗鼤?huì)不斷請(qǐng)求處理器周期地執(zhí)行檢查,
//更佳的技術(shù)是:使用Java的內(nèi)置“通知-等待”機(jī)制
while ( suspended ) {
Thread.sleep(200);
}
}
public static void main(String[] args) {
AlternateSuspendResume asr =
new AlternateSuspendResume();
Thread t = new Thread(asr);
t.start();
//休眠1秒,讓其他線程有機(jī)會(huì)獲得執(zhí)行
try { Thread.sleep(1000); }
catch ( InterruptedException x ) { }
for ( int i = 0; i < 10; i++ ) {
asr.suspendRequest();
//讓線程有機(jī)會(huì)注意到掛起請(qǐng)求
//注意:這里休眠時(shí)間一定要大于
//stepOne操作對(duì)firstVal賦值后的休眠時(shí)間,即300ms,
//目的是為了防止在執(zhí)行asr.areValuesEqual()進(jìn)行比較時(shí),
//恰逢stepOne操作執(zhí)行完,而stepTwo操作還沒(méi)執(zhí)行
try { Thread.sleep(350); }
catch ( InterruptedException x ) { }
System.out.println("dsr.areValuesEqual()=" +
asr.areValuesEqual());
asr.resumeRequest();
try {
//線程隨機(jī)休眠0~2秒
Thread.sleep(
( long ) (Math.random() * 2000.0) );
} catch ( InterruptedException x ) {
//略
}
}
System.exit(0); //退出應(yīng)用程序
}
}
運(yùn)行結(jié)果如下:

線程掛起的位置不確定main線程中執(zhí)行asr.areValuesEqual()進(jìn)行比較時(shí),恰逢stepOne操作執(zhí)行完,而stepTwo操作還沒(méi)執(zhí)行)asr.areValuesEqual()操作前,讓main線程休眠450ms(>300ms),如果掛起請(qǐng)求發(fā)出時(shí),新線程正執(zhí)行到或即將執(zhí)行到stepOne操作(如果在其前面的話,就會(huì)響應(yīng)掛起請(qǐng)求,從而掛起線程),那么在stepTwo操作執(zhí)行前,main線程的休眠還沒(méi)結(jié)束,從而main線程休眠結(jié)束后執(zhí)行asr.areValuesEqual()操作進(jìn)行比較時(shí),stepTwo操作已經(jīng)執(zhí)行完,因此也不會(huì)出現(xiàn)輸出結(jié)果為false的情況。
可以將ars.suspendRequest()代碼后的sleep代碼去掉,或?qū)⑿菝邥r(shí)間改為200(明顯小于300即可)后,查看執(zhí)行結(jié)果,會(huì)發(fā)現(xiàn)結(jié)果中依然會(huì)有出現(xiàn)false的情況。如下圖所示:

總結(jié):線程的掛起和恢復(fù)實(shí)現(xiàn)的正確方法是:通過(guò)設(shè)置標(biāo)志位,讓線程在安全的位置掛起
終止線程
終止線程的替代方法:同樣是使用標(biāo)志位,通過(guò)控制標(biāo)志位來(lái)終止線程。
以上所述是小編給大家介紹的Java 并發(fā)編程之線程掛起、恢復(fù)與終止,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Spring gateway配置Spring Security實(shí)現(xiàn)統(tǒng)一權(quán)限驗(yàn)證與授權(quán)示例源碼
這篇文章主要介紹了Spring gateway配置Spring Security實(shí)現(xiàn)統(tǒng)一權(quán)限驗(yàn)證與授權(quán),本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
Tomcat服務(wù)無(wú)法啟動(dòng)的問(wèn)題的解決方法
這篇文章主要介紹了Tomcat服務(wù)無(wú)法啟動(dòng)的問(wèn)題的解決方法,需要的朋友可以參考下2014-02-02
詳解使用Spring3 實(shí)現(xiàn)用戶登錄以及權(quán)限認(rèn)證
這篇文章主要介紹了詳解使用Spring3 實(shí)現(xiàn)用戶登錄以及權(quán)限認(rèn)證,這里整理了詳細(xì)的代碼,有需要的小伙伴可以參考下。2017-03-03
spring boot validation參數(shù)校驗(yàn)實(shí)例分析
這篇文章主要介紹了spring boot validation參數(shù)校驗(yàn),結(jié)合實(shí)例形式分析了spring boot validation進(jìn)行數(shù)據(jù)有效性驗(yàn)證的相關(guān)操作技巧,需要的朋友可以參考下2019-11-11
使用@RequestBody傳遞多個(gè)不同對(duì)象方式
這篇文章主要介紹了使用@RequestBody傳遞多個(gè)不同對(duì)象方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
MybatisPlus?BaseMapper?實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)增刪改查源碼
MybatisPlus?是一款在?Mybatis?基礎(chǔ)上進(jìn)行的增強(qiáng)?orm?框架,可以實(shí)現(xiàn)不寫(xiě)?sql?就完成數(shù)據(jù)庫(kù)相關(guān)的操作,這篇文章主要介紹了MybatisPlus?BaseMapper?實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)增刪改查源碼解析,需要的朋友可以參考下2023-01-01
Java實(shí)現(xiàn)簡(jiǎn)單小畫(huà)板
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡(jiǎn)單小畫(huà)板,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06

