死锁
2019-07-07 23:44 更新
过多的同步方法可能造成死锁。 MyThread:主程序。 Test1:卖家。 Test2:买家。 场景:一手给钱,一手给货,两者都拿着各自的锁不松手。造成死锁,无输出。
public class MyThread{
public static void main(String[] args) throws InterruptedException {
Object goods = new Object();
Object money = new Object();
Test1 t1 = new Test1(goods, money);
Test2 t2 = new Test2(goods, money);
new Thread(t1).start();
new Thread(t2).start();
}
}
class Test1 implements Runnable {
Object goods;
Object money;
public Test1(Object goods, Object money) {
this.goods = goods;
this.money = money;
}
@Override
public void run() {
while(true) {
test();
}
}
public void test() {
synchronized(goods) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (money) {
}
//注:这里已经有了商品,即Test1是卖家,需要给钱才能给货(goods的锁)。
System.out.println("一手给钱");
}
}
}
class Test2 implements Runnable {
Object goods;
Object money;
public Test2(Object goods, Object money) {
this.goods = goods;
this.money = money;
}
@Override
public void run() {
while(true) {
test();
}
}
public void test() {
synchronized(money) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (goods) {
}
//注:这里已经有了钱,即Test2是买家,需要给货才能给钱(money的锁)。
System.out.println("一手给货");
}
}
}
以上内容是否对您有帮助:
← 同步:并发
更多建议: