gpt4 book ai didi

java - 线程中的 Stop() 方法?

转载 作者:行者123 更新时间:2023-12-02 09:07:13 26 4
gpt4 key购买 nike

下面的例子中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.");
}
}

最佳答案

如果线程返回run()函数,线程会自动停止。不需要使用stop()函数,因为stop方法已被java弃用并且使用不安全

关于java - 线程中的 Stop() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7038063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com