다음 예제에서는 어떻게 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.");
}
}
를 사용하고 있기 때문에 정지() 함수를 사용할 필요가 function.no 반환하는 경우 스레드가 자동으로 중지 사용을 고려하기 전에 실제로 무엇을하는지 이해해야합니다. Thread.stop()은 항상 스레드를 중지하지는 않습니다. ;) –
@Peter : 모든 조건에서 Thread.stop()은 Thread를 죽이지 않을 것인가? – Logan
ThreadDeath를 잡으면 ThreadDeath 오류가 발생하고 ThreadDeath 또는 Error 또는 Throwable을 더 많이 기록하면 버려 질 수 있습니다. 자세한 내용은 내 대답의 기사를 참조하십시오. –