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()重新启动线程。
添加回答
举报
