W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
過多的同步方法可能造成死鎖。 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) {
}
//注:這里已經(jīng)有了商品,即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) {
}
//注:這里已經(jīng)有了錢,即Test2是買家,需要給貨才能給錢(money的鎖)。
System.out.println("一手給貨");
}
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: