Java SE之旅_04_死锁

当有多个线程访问多个共享资源时会发生死锁,那死锁是如何产生的呢?

用Java模拟如下:

/**
 * 死锁
 */
class  DeadLock implements Runnable
{
	private   boolean  flag;
	public DeadLock(boolean flag)
	{
		this.flag=flag;
	}
	public void run()
	{
		if(flag)
		{
			synchronized(MyLock.obj1)//-->obj1    (1)
			{
				System.out.println(Thread.currentThread().getName()+"if................obj1");
				synchronized(MyLock.obj2)//  出现死锁,obj2已给(2)拿了......等待(2)放开obj2.....   (3)
				{
					System.out.println("if.......obj2");
				}
			}
		}
		else
		{
			synchronized(MyLock.obj2)//-->obj2   (2)  
			{
				System.out.println(Thread.currentThread().getName()+"else................obj2");
				synchronized(MyLock.obj1)//出现死锁,obj1已给(1)拿了......等待(1)放开obj1.....   (4)
				{
					System.out.println("else.......obj1");
				}
			}
		}
	}
}

测试一把:

	public static void main(String[] args) 
	{
		DeadLock lock1 = new DeadLock(true);
	    DeadLock lock2 = new DeadLock(false);
		Thread t1 = new Thread(lock1);
		Thread t2 = new Thread(lock2);
		t1.start();
		t2.start();
	}


运气好的话你会看到这样子:


运气更好的话你会发现控制台一直没反应,根本停不下来!这就是传说中的死锁了:





你可能感兴趣的:(java,死锁,se)