java 之死锁认识

没有同步就不会造成死锁,过多的同步会造成死锁。

 

 

下面这个可能会造成死锁,

package com.bjszt.thread.create;

//过多的同步方法可能造成死锁
public class SynDemo03 {

public static void main(String[] args) {
Object goods = new Object();
Object money = new Object();
// TODO 自动生成的方法存根
Test t = new Test(goods, money);
Test1 t1 = new Test1(goods, money);
Thread proxy = new Thread(t);
Thread proxy1 = new Thread(t1);
proxy.start();
proxy1.start();
}
}

class Test implements Runnable {
Object goods;
Object money;

public Test(Object goods, Object money) {
this.goods = goods;
this.money = money;
}

public void run() {
// TODO 自动生成的方法存根
while (true) {
test();
}
}

public void test() {
synchronized (goods) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
synchronized (money) {

}
System.out.println(“一手给钱”);
}
}

class Test1 implements Runnable {
Object goods;
Object money;

public Test1(Object goods, Object money) {
this.goods = goods;
this.money = money;
}

public void run() {
// TODO 自动生成的方法存根
while (true) {
test();
}
}

public void test() {
synchronized (money) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
synchronized (goods) {

}
System.out.println(“一手给货”);
}
}

    原文作者:java锁
    原文地址: https://www.cnblogs.com/1130136248wlxk/articles/5248885.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞