Java deadlock

deadlock

Java does not provide language-level support for deadlocks, and deadlocks can only be avoided by careful design.

Example:
public class DeadLock implements Runnable {    
    public int flag = 1;    
    // static objects are shared by all objects of the class    
    private static Object o1 = new Object(), o2 = new Object();    
    @Override    
    public void run() {
        System.out.println("flag=" + flag);    
        if (flag == 1) {    
            synchronized (o1) {
                try {    
                    Thread.sleep(500);    
                } catch (Exception e) {    
                    e.printStackTrace ();    
                }    
                synchronized (o2) {    
                    System.out.println("1");    
                }    
            }    
        }    
        if (flag == 0) {    
            synchronized (o2) {    
                try {    
                    Thread.sleep(500);    
                } catch (Exception e) {    
                    e.printStackTrace ();    
                }    
                synchronized (o1) {    
                    System.out.println("0");    
                }    
            }    
        }    
    }    
    public static void main(String[] args) {    
            
        DeadLock td1 = new DeadLock();    
        DeadLock td2 = new DeadLock();    
        td1.flag = 1;    
        td2.flag = 0;    
        //td1, td2 are in the executable state, but it is uncertain which thread is executed first by the JVM thread scheduling.    
        //td2's run() may run before td1's run()    
        new Thread(td1).start();    
        new Thread(td2).start();    
    }    
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326260808&siteId=291194637