标签:java ar strong art sp on c ad new
/*
 * 演示死锁:(由毕向东视频所得)
 * 一种解释:Thread—0拿到lock1锁,Thread—1拿到lock2锁,Thread—0想要lock2锁而Thread-1想要lock1锁,
 * 两个线程都无法继续执行下去,产生死锁。
 * 执行结果:Thread-0 if.....lock1
 *      Thread-1 else....lock2
 */
package com.dld;
public class DeadLockDemo {
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Test a=new Test(true);
		Test b=new Test(false);
		Thread t1=new Thread(a);
		Thread t2=new Thread(b);
		t1.start();
		t2.start();
	}
}
class MyLock
{
	public static final Object lock1=new Object();
	public static final Object lock2=new Object();
	
}
class Test implements Runnable
{
	private boolean flag;
	public Test(boolean flag)
	{
		this.flag=flag;
	}
	public void run()
	{
		if(flag)
		{
			while(true)
			synchronized (MyLock.lock1) 
			{
				System.out.println(Thread.currentThread().getName()+" if.....lock1");
				synchronized (MyLock.lock2) 
				{
					System.out.println(Thread.currentThread().getName()+" if....lock2");
				}
			}
		}else{
			while(true)
			synchronized (MyLock.lock2) 
			{
				System.out.println(Thread.currentThread().getName()+" else....lock2");
				
				synchronized (MyLock.lock1) 
				{
					System.out.println(Thread.currentThread().getName()+" else.....lock1");
				}
			}
		}
	}
}
标签:java ar strong art sp on c ad new
原文地址:http://www.cnblogs.com/ql211lin/p/3971948.html