请让我知道以下程序是否会导致死锁?以下是详细信息:
线程: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();
    }
}

最佳答案

这似乎为我工作,这是Intellij中的线程转储:

关于java - 保证死锁,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19990187/

10-13 03:22