gpt4 book ai didi

java - 如何停止其 run() 没有循环的线程

转载 作者:行者123 更新时间:2023-11-29 05:37:29 25 4
gpt4 key购买 nike

如何停止 run() 没有循环的线程。所以基本上我想要替换 stop() 方法。当出现死锁时,我想停止其中一个线程。我不想使用锁。只想杀死一个线程,以便释放资源,其他线程将继续运行,从而结束程序。

我仍然尝试使用 stop() 但即使这样也没有停止程序。

以下是我的代码:-

public class Deadlock {

public static boolean stop = false;

public static void main(String[] args) {
final String resource1 = "resource1";
final String resource2 = "resource2";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
// Lock resource 1
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");

try {
Thread.sleep(50);
} catch (InterruptedException e) {
}

synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");

try {
Thread.sleep(50);

} catch (InterruptedException e) {
}

synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}

}
}
};

// If all goes as planned, deadlock will occur,
// and the program will never exit.
t1.start();
t2.start();

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

if(t1.isAlive() && t2.isAlive())
{
System.out.println("Deadlock");
// t1.stop(); Deprecated
}
}
}

最佳答案

除了实际修复错误之外,您无法修复错误。如果线程有错误,则必须修复错误,否则它会污染进程上下文。

参见 this answer这只是从外部进入线程并释放其锁不安全的原因之一。此外,link在 dst 的评论中非常有帮助。

关于java - 如何停止其 run() 没有循环的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18950884/

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