我是一名Java新手,我一直在努力学习多线程及其用法。在多线程中,我试图了解死锁并编写了一个程序来执行此操作。问题是条件死锁方法仍然返回false
,这意味着没有检测到死锁。我希望有人能提供帮助。
这是我的程序产生死锁。
public class DeadlockGenerator {
private Object firstLockObject = new Object();
private Object secondLockObject = new Object();
public void generateDeadlock() {
Thread threadOne = new Thread(new Runnable() {
@Override
public void run() {
synchronized(firstLockObject) {
System.out.println("Thread1 on first lock object");
synchronized(secondLockObject) {
System.out.println("Thread2 on second lock object");
}
}
}
});
threadOne.start();
Thread threadTwo = new Thread(new Runnable() {
@Override
public void run() {
synchronized(secondLockObject) {
System.out.println("Thread2 on second lock object");
synchronized(firstLockObject) {
System.out.println("Thread1 on first lock object");
}
}
}
});
threadTwo.start();
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {}
}
}
这是我检测死锁的程序
public class DeadlockThread {
private final ThreadMXBean bean;
DeadlockThread(ThreadMXBean bean) {
this.bean = bean;
}
/**
* Returns the the number of dead locked threads.
* @return number of deadlocked threads
*/
public int numberOfDeadlockedThreads() {
long [] deadlockThreadIds = this.bean.findMonitorDeadlockedThreads();
return deadlockThreadIds == null ? 0 : deadlockThreadIds.length;
}
}
这是我调用死锁和检测的函数。
/**
* Initiates a deadlock and checks if it still exists after {@code timeInSeconds} have elapsed.
*
* @param timeInSeconds time in seconds
* @return {@code true} if deadlock is detected; {@code false} otherwise
*/
static boolean startAndDetectDeadlocks(int timeInSeconds) {
new DeadlockGenerator().generateDeadlock();
try {
Thread.sleep(timeInSeconds * 1000);
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
DeadlockThread dt = new DeadlockThread(bean);
return dt.numberOfDeadlockedThreads() > 0;
} catch (InterruptedException e) {
}
return false;
}
调试后,我注意到以下问题。以下代码行
long [] deadlockThreadIds = this.bean.findMonitorDeadlockedThreads();
始终返回null
。
我不知道自己做错了什么,我很感谢你在这件事上提供任何帮助。
答案 0 :(得分:1)
findMonitorDeadlockedThreads
方法 - 返回监视器死锁的线程的ID数组(如果有);否则为null。
我猜这里没有发生死锁情况,thread1完成并在thread2开始运行之前退出。
在获取firstLockObject
后尝试在线程1中放置一些休眠时间。这样线程2就有机会运行并获得secondLockObject
。
Thread threadOne = new Thread(new Runnable() {
@Override
public void run() {
synchronized(firstLockObject) {
System.out.println("Thread1 on first lock object");
try {
Thread.sleep(1000);
} catch (InterruptedException ex){
// do nothing...
}
synchronized(secondLockObject) {
System.out.println("Thread2 on second lock object");
}
}
}
});
此更改后,numberOfDeadlockedThreads返回为2。