如何停止 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
}
}
}