论坛首页 入门技术论坛

写死锁的郁闷

浏览 2000 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-04-02  
这段时间在看马士兵老师的关于线程同步的教程,完了自己想写一个死锁出来,按照马老师的精髓,我写了下面的代码,但我无论如何也没法将它锁死,下面是代码希望大家帮忙看下是什么原因,我感谢万分!!!!(jdK版本:6.0)
package cn.zhangxuemin.j2se;

public class TestDeadLock implements Runnable{
	static int flag  ;
	static Object o1 = new Object();
	static Object o2 = new Object();
	public void run () {
		System.out.println("flag= "+flag);
		if(flag==2) {
			synchronized (o1) {
				System.out.println("i am object 1");
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				synchronized (o2) {
					System.out.println("i am object 2");
				}
			}
		}
		if(flag==1) {
			synchronized (o2) {
				System.out.println("i am object 222");
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (o1) {
					System.out.println("i am object 111");
				}
			}
		}
	}
	
	public static void main(String[] args) {
		TestDeadLock test1 = new TestDeadLock();
		TestDeadLock test2 = new TestDeadLock();
		
		
		Thread t1 = new Thread(test1);
		Thread t2 = new Thread(test2);
		flag = 1;
		t1.start();
		flag = 2;
		t2.start();
	}
	
}


运行结果:
flag= 2
i am object 1
flag= 2
i am object 2
i am object 1
i am object 2
   发表时间:2009-03-12  
这样改就行:
public class TestDeadLock implements Runnable{   
    int flag  ;   
    static Object o1 = new Object();   
    static Object o2 = new Object(); 
    TestDeadLock(int i)
    {
    	this.flag=i;
    }
    
    public void run () {   
        System.out.println("flag= "+flag);   
        if(flag==2) {   
            synchronized (o1) {   
                System.out.println("i am object 1");   
                try {   
                    Thread.sleep(500);   
                } catch (InterruptedException e) {   
                    e.printStackTrace();   
                }   
                   
                synchronized (o2) {   
                    System.out.println("i am object 2");   
                }   
            }   
        }   
        if(flag==1) {   
            synchronized (o2) {   
                System.out.println("i am object 222");   
                try {   
                    Thread.sleep(500);   
                } catch (InterruptedException e) {   
                    e.printStackTrace();   
                }   
                synchronized (o1) {   
                    System.out.println("i am object 111");   
                }   
            }   
        }   
    }   
       
    public static void main(String[] args) {   
        TestDeadLock test1 = new TestDeadLock(1);   
        TestDeadLock test2 = new TestDeadLock(2);   
           
           
        Thread t1 = new Thread(test1);   
        Thread t2 = new Thread(test2);   
        t1.start();   
        t2.start();   
    }   
       
}  

 

0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics