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

zbb20180913 java thread 死锁示例代码

时间:2018-09-13 16:24:07      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:ack   ace   over   trace   exce   string   dea   test   static   

package com.zbb.test.thread;

public class DeadLock {
	public static String obj1 = "obj1";
	public static String obj2 = "obj2";

	public static void main(String[] args) {
		Thread a = new Thread(new Lock1());
		Thread b = new Thread(new Lock2());
		a.start();
		b.start();
	}
}

class Lock1 implements Runnable {
	@Override
	public void run() {
		try {
			System.out.println("Lock1 running");
			while (true) {
				synchronized (DeadLock.obj1) {
					System.out.println("Lock1 lock obj1");
					Thread.sleep(3000);// 获取obj1后先等一会儿,让Lock2有足够的时间锁住obj2
					synchronized (DeadLock.obj2) {
						System.out.println("Lock1 lock obj2");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class Lock2 implements Runnable {
	@Override
	public void run() {
		try {
			System.out.println("Lock2 running");
			while (true) {
				synchronized (DeadLock.obj2) {
					System.out.println("Lock2 lock obj2");
					Thread.sleep(3000);
					synchronized (DeadLock.obj1) {
						System.out.println("Lock2 lock obj1");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

  

zbb20180913 java thread 死锁示例代码

标签:ack   ace   over   trace   exce   string   dea   test   static   

原文地址:https://www.cnblogs.com/super-admin/p/9640663.html

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