在下面的示例中,stop()
方法是如何实现的?线程中的Stop()方法?
应该做些什么而不是使用stop()
方法?
在我看来,当期望的状态被挂起时,线程将使用Object.wait
等待。当线程恢复时,使用Object.notify
来通知目标线程。但在下例中实施stop()
的情况令人怀疑。
Class NewThread implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized(this) {
while(suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
notify();
}
}
class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
System.out.println("Resuming thread One");
ob2.mysuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.myresume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
使用Thread.stop已过时,你的线程自动停止在考虑使用它之前,需要了解它的真实含义。 Thread.stop()并不总是停止一个线程。 ;) –
@Peter:在什么情况下Thread.stop()不会杀死一个线程? – Logan
Thread.stop()抛出一个ThreadDeath错误,如果你抓住ThreadDeath或Error或Throwable(更可能)它可以被记录和丢弃。请参阅我的答案中的文章了解更多信息。 –