codecamp

死锁

过多的同步方法可能造成死锁。 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("一手给货");
        }
    }
}
同步:并发
生产者消费者
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }