Java死锁代码示例

来源:互联网 发布:ubuntu iptables 重启 编辑:程序博客网 时间:2024/05/21 03:55
public class ThreadTest implements Runnable{    boolean flag;   ThreadTest(boolean flag){       this.flag=flag;    }    public void run() {       if(flag)        {            synchronized (MyLock.locka)            {                System.out.println("if locka");                    synchronized (MyLock.lockb)                    {                        System.out.println("if lockb");                        flag=false;                    }            }        }        else       {           synchronized (MyLock.lockb)           {               System.out.println("else lockb");               synchronized (MyLock.locka)               {                   System.out.println("else locka");               }           }       }    }

}

public class MyLock {    public static Object locka=new Object();    public static Object lockb=new Object();}
public static void main(String[] args) {
  Thread t1=new Thread(new ThreadTest(true));      Thread t2=new Thread(new ThreadTest(false));        t1.start();        t2.start();    }}