我已經創建的對象的列表,並且還線程列表發送所述參數是從該列表中隨機對象。一旦線程被創建,線程應該鎖定在參數中傳遞的對象。但是,儘管我在創建線程後形成死鎖,但已將線程設置爲睡眠。似乎沒有形成任何僵局。基於一些谷歌的研究,我瞭解到對象是在Java中通過引用,但我不知道爲什麼它不在這裏工作。爪哇:通過對象在參數指針(通過引用傳遞)
for(int i=0;i<5;i++){
Object tempObject = new Object();
objectList.add(tempObject);
}
Random rand = new Random();
for(int i =0;i<5;i++){
for(int j =0;j<10;j++){
int random = rand.nextInt(objectList.size());
CustomThread ct = new CustomThread(i,objectList.get(random));
ct.start();
System.out.println();
}
try {
detectDeadlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void detectDeadlock() throws InterruptedException {
while(true){
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
long[] threadIds = threadBean.findDeadlockedThreads();
int deadlockedThreads = threadIds != null? threadIds.length : 0;
System.out.println("Number of deadlocked threads: " + deadlockedThreads);
TimeUnit.MILLISECONDS.sleep(1000);
}
}
CustomThread.java
NewThread(int processID, Object tObject) {
this.pid = processID;
this.object = tObject;
}
@Override
public void run() {
synchronized (this.object) {
Random rand = new Random();
System.out.println("Holding an object");
try { TimeUnit.MILLISECONDS.sleep(rand.nextInt(10000)); }
catch (InterruptedException e) {}
}
}
什麼是'detectDeadlock'? –
@PaulBoddington我也加了這個方法。 –