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("一手给货");
}
}
posted on 2016-03-06 22:33 1130136248 阅读(76) 评论(0) 编辑 收藏 举报