以下のプログラムがデッドロックを保証するかどうか教えてください。以下に詳細を示します。 スレッド: process1 および process2。オブジェクト: スキャナーとプリンター。process1 はスキャナーとプリンターの両方をロックしますが、スキャナーを断念します。process2 はスキャナーをロックしますが、process1 がロックしているため、プリンターを取得できません。おそらく私のスレッドの概念は不明確ですが、どこが間違っているのか教えてください。
class DeadLock extends Thread {
//creating a scanner object
private static Object scanner = new Object();
//creating a printer object
private static Object printer = new Object();
//the process name
private String processName;
//initializes process2 is not created yet
private boolean process2IsCreated = false;
/**
* the constructor which sets string to process1 or 2
* @param string
*/
public DeadLock(String string) {
// TODO Auto-generated constructor stub
this.processName = string;
}
/**
* deadlock() for process1
*/
public void deadlock1() {
//process1 locks scanner
synchronized (scanner) {
//process1 locks printer, too
synchronized (printer) {
//create process2 after process1
if(process2IsCreated == false && processName.equals("process1")) {
new DeadLock("process2").start();
process2IsCreated = true;
}
try {
//process1 is waiting on scanner and releases its monitor.
//After regaining access, process1 tries to acquire scanner
//but cannot do so because process2 has locked it already.
//. . .too late, process1!
scanner.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* deadlock() for process2
*/
public void deadlock2() {
//process2 locks scanner
synchronized (scanner) {
//process2 notifies process1 which is waiting on scanner
scanner.notify();
//process2 locks printer, but cannot lock printer because process1 has it
//. . .too late, process2!
synchronized (printer) {
}
}
}
/**
* both threads are scheduled to execute run()
*/
public void run() {
//if process1 then enter deadlock1()
if(processName.equals ("process1")) deadlock1();
//if process 2 then enter deadlock2()
else deadlock2();
}
/**
* the main method which creates thread process1
* @param a
*/
public static void main(String a[]) {
new DeadLock("process1").start();
}
}