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...");
}
}

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