zbb20180913 java thread 死锁示例代码

Posted Daryll

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了zbb20180913 java thread 死锁示例代码相关的知识,希望对你有一定的参考价值。

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 死锁示例代码的主要内容,如果未能解决你的问题,请参考以下文章

zbb20180929 thread java并发编程之Condition

zbb20171214 java 获取classpath路径

zbb20180929 thread notify()与notifyAll()的区别

zbb20180929 thread 自旋锁阻塞锁可重入锁悲观锁乐观锁读写锁对象锁和类锁

java 多线程死循环怎么动态传参?急!

java Thread.sleep卡死问题