java synchronized死锁的好例子

关于java死锁的一个好demo。要避免dead-lock,就应该控制同步的数量和可能共用的资源的访问(代码源于网上,略加修改)

/**
 * @author yicong
 * @date 2016年3月22日 下午1:44:32
 * @todo 死锁的经典例子
 */
public class DeadLock {

	public static void main(String[] args) {

		// These are the two resource objects we'll try to get locks for
		final Object resource1 = "resource1";
		final Object resource2 = "resource2";

		// Here's the first thread. It tries to lock resource1 then resource2
		Thread t1 = new Thread() {

			public void run() {

				// Lock resource 1
				synchronized (resource1) {
					System.out.println("Thread 1: locked resource 1");
					
					// Pause for a bit, simulating some file I/O or
					// something. Basically, we just want to give the
					// other thread a chance to run. Threads and deadlock
					// are asynchronous things, but we're trying to force
					// deadlock to happen here...
					try {
						Thread.sleep(50);
					}catch (InterruptedException e) {
					
					}

					// Now wait 'till we can get a lock on resource 2
					synchronized (resource2) {

						while (true) {
							System.out.println("Thread 1: locked resource 2");

							try {
								Thread.sleep(10000);
							}catch (InterruptedException e) {
							}
						}
					}
				}
			}
		};

		// Here's the second thread. It tries to lock resource2 then resource1
		Thread t2 = new Thread() {

			public void run() {

				// This thread locks resource 2 right away
				synchronized (resource2) {
					System.out.println("Thread 2: locked resource 2");

					// Then it pauses, just like the first thread.
					try {
						Thread.sleep(50);
					}catch (InterruptedException e) {
					}

					// Then it tries to lock resource1. But wait! Thread 1
					// locked resource1, and won't release it 'till it
					// gets a lock on resource2. This thread holds the
					// lock on resource2, and won't release it 'till it
					// gets resource1. We're at an impasse(僵局). Neither
					// thread can run, and the program freezes up.
					
					synchronized (resource1) {
						System.out.println("Thread 2: locked resource 1");
					}
				}
			}
		};

		// Start the two threads. If all goes as planned, deadlock will occur, and the program will never exit.
		t1.start();
		t2.start();
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值