亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如下,按照2L的方法會new出一個新的線程,但是原來的線程都不能運行了?為什么?

如下,按照2L的方法會new出一個新的線程,但是原來的線程都不能運行了?為什么?

神不在的星期二 2022-05-20 12:15:35
class A extends Thread{static class B{我想在這里調用suspend()方法來停止線程A,該怎么做}}
查看完整描述

2 回答

?
呼如林

TA貢獻1798條經驗 獲得超3個贊

suspend()該方法在jdk1.6中已經不推薦使用了,過時了。如果是非阻塞線程只加①句,“使用一個共享變量,線程周期性檢測這一變量的值”。如果線程被阻塞,它便不能核查共享變量,也就不能停止。因此不加①只加②即可實現。
class A extends Thread
{
volatile boolean stop = false;

static class B
{
public void du() throws Exception
{
A thread = new A();
System.out.println("Starting thread...");
thread.start();
Thread.sleep(3000);
System.out.println("Asking thread to stop...");
thread.stop = true; // ①
thread.interrupt(); // ②
Thread.sleep(3000);
System.out.println("Stopping application...");
// System.exit( 0 );
}
}

public void run()
{
while (!stop)
{
System.out.println("Thread running...");
try
{
Thread.sleep(1000); // 模擬線程被阻塞
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted...");
}
}
System.out.println("Thread exiting under request...");
}
}



查看完整回答
反對 回復 2022-05-23
?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

suspend()方法容易發生死鎖。調用suspend()的時候,目標線程會停下來,但卻仍然持有在這之前獲得的鎖定。此 時,其他任何線程都不能訪問鎖定的資源,除非被"掛起"的線程恢復運行。對任何線程來說,如果它們想恢復目標線程,同時又試圖使用任何一個鎖定的資源,就 會造成死鎖。所以不應該使用suspend(),而應在自己的Thread類中置入一個標志,指出線程應該活動還是掛起。若標志指出線程應該掛起,便用 wait()命其進入等待狀態。若標志指出線程應當恢復,則用一個notify()重新啟動線程。

查看完整回答
反對 回復 2022-05-23
  • 2 回答
  • 0 關注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號