请问我可以知道下面的程序是否保证死锁吗?下面给出了详细信息: 线程: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();
}
}