java写一个死锁

本文通过一个具体的Java代码示例,详细解析了死锁的发生过程。两个线程分别持有不同的对象锁,在尝试获取对方持有的锁时陷入无限等待,从而形成死锁。文章深入探讨了死锁的成因及预防策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * @author JZWen
 * @date  2019年2月24日
 */

/**
 * @author JZWen
 *
 */
public class DeathLock {

	/**
	 * @param args
	 */
	public static void run() {
		MyThread mThread = new MyThread(true);
		new Thread(mThread, "jzw").start();
		new Thread(mThread , "cjj").start();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		run();
	}
}

class MyThread implements Runnable{

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	
	Object o1 =  new Object();
	Object o2 =  new Object();
	boolean sign = true;
	

	/**
	 * 2019-02-24 15:32:47
	 * 构造函数
	 */
	public MyThread(boolean sign) {
		// TODO Auto-generated constructor stub
		this.sign = sign;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		/**
		 * 重点
		 */
		if(sign) {
			sign = false;
			//获取o1锁
			synchronized (o1) {
				//然后我们sleep,然后在打印线程名
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("当前线程名:"+Thread.currentThread().getName());
				//之后我们在没有释放o1锁的情况下,去获取o2锁。
				synchronized (o2) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("当前线程名:"+Thread.currentThread().getName());
				}
			}
		}
		
		if(!sign) {
			sign = true;
			//获取o1锁
			synchronized (o2) {
				//然后我们sleep,然后在打印线程名
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("当前线程名:"+Thread.currentThread().getName());
				//之后我们在没有释放o1锁的情况下,去获取o2锁。
				synchronized (o1) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("当前线程名:"+Thread.currentThread().getName());
				}
			}
		}
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值