- //主函数
- public static void main(String[] args) {
- SiSuo si = new SiSuo(false); //创建了死锁的对象
- Thread t1 = new Thread(si);//建立俩线程
- Thread t2 = new Thread(si);
- t1.start();
- try{Thread.sleep(10);}catch(Exception e){}
- si.setFlag(true);
- t2.start();
- class MyLock //先创建了锁的类
- {
- Object obj1 = new Object();
- Object obj2 = new Object();
- }
- class SiSuo implements Runnable//死锁程序
- {
- MyLock my = new MyLock();//创建了锁的对象
- private boolean flag;
- SiSuo(boolean flag)
- {
- this.flag = flag;
- }
- public void setFlag(boolean flag)
- {
- this.flag=flag;
- }
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(my.obj1)//对象调用
- {
- System.out.println("code lock1");
- synchronized(my.obj2)
- {
- System.out.println("code lock2");
- }
- }
- }
- }
- else
- {
- while(true)
- {
- synchronized(my.obj2) //和if里面的my.obj2不一样么?
- {
- System.out.println("else lock2");
- synchronized(my.obj1)
- {
- System.out.println("else lock1");
- }
- }
- }
- }
- }
- }
复制代码 结果如下:
|
|