码迷,mamicode.com
首页 > 编程语言 > 详细

产生死锁代码 - Java

时间:2014-09-14 15:25:01      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:多线程

public static void main(String[] args) {
		final LeftRightDeadLock lock = new LeftRightDeadLock();
		new Thread(){
			@Override
			public void run() {
				lock.leftRight();
			}
		}.start();
		
		new Thread(){
			@Override
			public void run() {
				lock.rightLeft();
			}
		}.start();
	}
}

class LeftRightDeadLock {
	private final Object left = new Object();
	private final Object right = new Object();

	public void leftRight() {
		
		synchronized (left) {
			System.out.println("leftRight got left lock");
			
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			synchronized (right) {
				System.out.println("leftRight got right lock");
			}
		}
	}

	public void rightLeft() {
		
		synchronized (right) {
			System.out.println("rightLeft got right lock");
			
			synchronized (left) {
				System.out.println("rightLeft got left lock");
			}
		}
	}
bubuko.com,布布扣

产生死锁代码 - Java

标签:多线程

原文地址:http://blog.csdn.net/stephenluu/article/details/39269951

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!