死锁解决

package deadLock;

public class SolveDeadLock implements Runnable
{
	public int flag = 1;
	static Object o1 = new Object(),o2 = new Object();
	public void run()
	{
		if (flag == 1)// 当flag==1锁住o1
		{
			System.out.println("t1线程启动:锁住了o1并去睡觉");
			synchronized (o1)
			{
				try
				{
					Thread.sleep(100);
				} 
				catch (Exception e)
				{
					e.printStackTrace();
				}
				System.out.println("t1线程醒来:等待着t2线程将o2的钥匙归还...");
				try 
				{
					o1.wait();//让线程t1出于等待状态
				} 
				catch (InterruptedException e) 
				{
					e.printStackTrace();
				}
				o1.notify();//唤醒线程t1
				synchronized (o2)// 只要锁住o2就完成
				{
					System.out.println("t2线程执行完任务后,将o2的钥匙归还给t1,t1线程拿到了钥匙,并执行完成了任务");
				}
			}
		}
		if (flag == 0)// 如果flag==0锁住o2
		{
			System.out.println("t2线程启动:锁住了o2并去睡觉");
			synchronized (o2)
			{
				try
				{
					Thread.sleep(100);
				} 
				catch (Exception e)
				{
					e.printStackTrace();
				}
				System.out.println("t2线程醒来:等待着t1线程将o1的钥匙归还...");
				synchronized (o1)
				{
					System.out.println("t2线程醒来执行完了任务");
					o1.notify();
				}
				
			}
			
		}
		
	}
	public static void main(String[] args)
	{
		SolveDeadLock td1 = new SolveDeadLock();
		SolveDeadLock td2 = new SolveDeadLock();
		td1.flag = 1;
		td2.flag = 0;
		new Thread(td1).start();
		 new Thread(td2).start();
	}
}

 

你可能感兴趣的:(thread)