java多线程死锁

package com.luowen.test;

public class DealLockTest {

	public static void main(String[] args) {
		Go g1 = new Go(true);
		Go g2 = new Go(false);
		
		Thread t1 = new Thread(g1);
		Thread t2 = new Thread(g2);
			t1.start();
			try{Thread.sleep(5);} catch(Exception e){}
			t2.start();
			
	}
}

class MyLock
{
	final public static Object locka = new Object();
	final public static Object lockb = new Object();
}

class Go implements Runnable
{

	private boolean flag;
	
	Go(boolean flag)
	{
		this.flag = flag;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		if(flag)
		{
			while(true)
			{
					synchronized (MyLock.locka)
				{
					System.out.println(Thread.currentThread().getName() + "================if get the locka");
					synchronized (MyLock.lockb) {
						System.out.println(Thread.currentThread().getName() + "================if get the locka and lockb");
					}
				}
			}
			
		}
		else
		{
			while(true)
			{
				synchronized (MyLock.lockb)
				{
					
					System.out.println(Thread.currentThread().getName() + "================else get the lockb");
					synchronized(MyLock.locka)
					{
						System.out.println(Thread.currentThread().getName() + "================else get the locka and lockb");
						
					}
				}
			}
		}
	}
}

  

    原文作者:arvim
    原文地址: http://www.cnblogs.com/luowen/p/3675976.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞