从头认识多线程-2.21 死锁简介

这一章节我们来展示一下死锁。

1.代码清单

package com.ray.deepintothread.ch02.topic_21;

/**
 * 
 * @author RayLee
 *
 */
public class DeadLock {
	public static void main(String[] args) throws InterruptedException {
		MyService myService = new MyService();
		ThreadOne threadOne = new ThreadOne(myService);
		Thread thread = new Thread(threadOne);
		thread.start();
		ThreadTwo threadTwo = new ThreadTwo(myService);
		Thread thread2 = new Thread(threadTwo);
		thread2.start();
	}
}

class ThreadOne implements Runnable {
	private MyService myService;

	public ThreadOne(MyService myService) {
		this.myService = myService;
	}

	@Override
	public void run() {
		try {
			myService.updateA();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class ThreadTwo implements Runnable {

	private MyService myService;

	public ThreadTwo(MyService myService) {
		this.myService = myService;
	}

	@Override
	public void run() {
		try {
			myService.updateB();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class MyService {
	private Object object1 = new Object();
	private Object object2 = new Object();

	public void updateA() throws InterruptedException {
		System.out.println(Thread.currentThread().getName());
		synchronized (object1) {
			System.out.println("synch obj1");
			Thread.sleep(1000);
			synchronized (object2) {
				System.out.println("synch obj2");
			}
		}

	}

	public void updateB() throws InterruptedException {
		System.out.println(Thread.currentThread().getName());
		synchronized (object2) {
			System.out.println("synch obj2");
			Thread.sleep(1000);
			synchronized (object1) {
				System.out.println("synch obj1");
			}
		}
	}

}

输出:

Thread-0
synch obj1
Thread-1
synch obj2

(然后一直等。。。。。)


2.死锁形成的条件

两个线程都持有对方所需要的锁,同时也等待对方释放自己需要的锁,形成线程假死状态


总结:这一章节只是简单的展示一下死锁,后面会有一个单独的大章来阐述锁的问题。


这一章节就到这里,谢谢

------------------------------------------------------------------------------------

我的github:https://github.com/raylee2015/DeepIntoThread


目录:http://blog.csdn.net/raylee2007/article/details/51204573


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值