伝説のデッドロック


 !synchronized , 。
/**
 * This is a demo of dead lock
 * 
 * @author Administrator
 * 
 */
public class SyncDemo
{
    public static void main(String[] args)
    {
	Person person = new Person();

	Thread t1 = new MyThread(person);
	Thread t2 = new MyThread2(person);

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

class MyThread extends Thread
{
    private Person person;

    public MyThread(Person person)
    {
	this.person = person;
    }

    @Override
    public void run()
    {
	person.method1();
    }
}

class MyThread2 extends Thread
{
    private Person person;

    public MyThread2(Person person)
    {
	this.person = person;
    }

    @Override
    public void run()
    {
	person.method2();
    }
}

class Person
{
    private Object obj = new Object();
    private Object o = new Object();

    public void method1()
    {
	synchronized (obj)
	{
	    for (int i = 0; i < 20; i++)
	    {
		try
		{
		    Thread.sleep((long) (Math.random() * 1000));
		}
		catch (InterruptedException e)
		{
		    e.printStackTrace();
		}
		method2();
		System.out.println(Thread.currentThread() + " : " + i);
	    }
	}
    }

    public void method2()
    {
	synchronized (o)
	{
	    for (int i = 0; i < 20; i++)
	    {
		try
		{
		    Thread.sleep((long) (Math.random() * 1000));
		}
		catch (InterruptedException e)
		{
		    e.printStackTrace();
		}
		method1();
		System.out.println(Thread.currentThread() + " : " + i);
	    }
	}
    }
}

もう一つはっきりした(北京尚学堂馬兵士先生の教程を見た後、思い出に基づいて書いた):
public class DeadLock
{
	public static void main(String[] args)
	{
		final T2 t = new T2();
		
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				System.out.println(" :" + Thread.currentThread().getName());
				t.test1();
			}			
		}).start();
		
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				System.out.println(" :" + Thread.currentThread().getName());
				t.test2();
			}			
		}).start();
	}
}

class T2
{
	private Object locker1 = new Object();
	private Object locker2 = new Object();
	
	public void test1()
	{
		synchronized (locker1)
		{
			System.out.println(" , locker1, locker2, ! !");
			try
			{
				Thread.sleep(1000);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			synchronized (locker2)
			{
				System.out.println(" , locker2, ! !");
			}
		}
	}
	
	public void test2()
	{
		synchronized (locker2)
		{
			System.out.println(" , locker2, locker1, ! !");
			try
			{
				Thread.sleep(1000);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			synchronized (locker1)
			{
				System.out.println(" , locker1, ! !");
			}
		}
	}
}