package com.cyj.thread.manage;
/**
* 在多个线程调用同一份资源,由于同步的过多,在两个调用资源处理时间不一致的情况下
* 因为同时调用并且不释放内存锁,造成死锁现象
*
* 所以:
* 不能一味的同步资源
* 生产者消费者模式产生
* @author Chyjrily
*
*/
public class MyDeadLock {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
Text t1 = new Text(o1,o2);
Text t2 = new Text(o1,o2);
Thread proxy = new Thread(t1); //Runnable proxy = new Thread(t1); 这么写是错误的,多态不能调用新增的方法
Thread proxy2 = new Thread(t2);
proxy.start();
proxy2.start();
}
}
class Text implements Runnable{
Object goods = new Object();
Object money = new Object();
public Text(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
public void run(){
while(true) {
text();
}
}
public void text() {
synchronized(goods) {
try {
Thread.sleep(10000); //为了两个资源调用的不一致,发生的死锁的概率提高,两个延时的时间设定要不一样
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(money) {
}
}
System.out.println("一手交钱");
}
}
class Text2 implements Runnable{
Object goods;
Object money;
public Text2(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
public void run(){
while(true) {
text();
}
}
public void text() {
synchronized(money) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(goods) {
}
}
System.out.println("一手交货");
}
同步造成死锁案例
猜你喜欢
转载自blog.csdn.net/qq_42036616/article/details/81083480
今日推荐
周排行