死索的java实现

public class DeadLockTest extends Thread
{
	private boolean flag = false;
	private static Object obj1 = new Object();
	private static Object obj2 = new Object();
	
	public static void main(String[] args)
	{
		DeadLockTest t1 = new DeadLockTest();
		DeadLockTest t2 = new DeadLockTest();
		t1.flag = true;
		t2.flag = false;

		t1.start();
		t2.start();
	}

	public void run()
	{
		System.out.println("flag = " + flag);
		if(flag)
		{
			synchronized(obj1)
			{
				try
				{
					Thread.sleep(500);
				} catch (InterruptedException e)
				{
					e.printStackTrace();
				}
				synchronized(obj2)
				{
					System.out.println("线程 1 成功");
				}
			}
		}
		
		if(!flag)
		{
			synchronized(obj2)
			{
				try
				{
					Thread.sleep(500);
				} catch (InterruptedException e)
				{
					e.printStackTrace();
				}
				synchronized(obj1)
				{
					System.out.println("线程 2 成功");
				}
			}
		}
	}
}

你可能感兴趣的:(java,多线程,死锁)