死锁示例程序

public class deadlock {
	/**一个简单的死锁类
	 * 在一个Runnable实现类中模拟两个进程的执行内容;
	 * 当flag == true时模块1(线程1)执行,先执行锁外程序(不受锁限制),再锁定锁1
	 * (str对象)执行100到1的输出,
	 * 然后锁定锁2(str1对象),即需要得到锁2才能继续执行;
	 * 当flag == false时模块2(线程2)执行,先锁定锁2(str1对象)执行1到100的输出,
	 * 然后锁定锁1(str对象),即需要得到锁1才能继续执行;
	 * 所以此时两个线程互相等待对方释放手里的锁,导致程序阻塞,造成死锁。
	 */
	public static void main(String[] args) {
		// TODO 自动生成方法存根
		deadtest tt0 = new deadtest();
		// TxtThread tt1 = new TxtThread();
		// TxtThread tt2 = new TxtThread();
		// TxtThread tt3 = new TxtThread();
		tt0.flag = false;
		new Thread(tt0).start();
		deadtest tt1 = new deadtest();
		tt1.flag = true;
		new Thread(tt1).start();
		// new Thread(tt0).start();
		// new Thread(tt0).start();
		// new Thread(tt1).start();
		// new Thread(tt2).start();
		// new Thread(tt3).start();
	}
}

class deadtest implements Runnable {

	static String str = new String();
	static String str2 = new String();
	boolean flag;

	public void run() {
		if (flag == true) {
			for (int i = 1; i <= 20; i++) {
				try {
					Thread.sleep(10);
				} catch (Exception e) {
					e.getMessage();
				}
				System.out.println("鎖之外");
			}
			synchronized (str) {
				int num = 100;
				while (num > 0) {
					try {
						Thread.sleep(10);
					} catch (Exception e) {
						e.getMessage();
					}
					System.out.println(Thread.currentThread().getName()
							+ "this is 模块1锁1 " + num--);
				}
				synchronized (str2) {
					int num2 = 100;
					for (int j = 0; j <= num2; j++) {
						try {
							Thread.sleep(10);
						} catch (Exception e) {
							e.getMessage();
						}
						System.out.println(Thread.currentThread().getName()
								+ "this is 模块1锁2 " + j);
					}
				}
			}

		}
		if (flag == false) {
			synchronized (str2) {
				int num2 = 100;
				for (int j = 0; j <= num2; j++) {
					try {
						Thread.sleep(10);
					} catch (Exception e) {
						e.getMessage();
					}
					System.out.println(Thread.currentThread().getName()
							+ "this is 模块2锁2 " + j);
				}
				synchronized (str) {

					int num = 100;
					while (num > 0) {
						try {
							Thread.sleep(10);
						} catch (Exception e) {
							e.getMessage();
						}
						System.out.println(Thread.currentThread().getName()
								+ "this is模块2锁1 " + num--);

					}
				}
			}

		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值