亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

synchronized同步方法沒鎖住成員變量是為什么

synchronized同步方法沒鎖住成員變量是為什么

精慕HU 2019-01-16 08:54:46
public class Test { public static void main(String[] args) { Account account=new Account(100); Person p1=new Person(account,80); Person p2=new Person(account,90); p1.start(); p2.start(); } } class Account{ int total; public Account(int total) { super(); this.total=total; } } class Person extends Thread{ private int reduce; public Account account; public Person(Account account,int reduce) { this.account=account; this.reduce=reduce; } public synchronized void run() { if (account.total-reduce<0) return ; try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } account.total-=reduce; System.out.println(Thread.currentThread().getName()+"取出"+reduce); System.out.println(Thread.currentThread().getName()+"剩余"+account.total); } } Thread-0取出80Thread-0剩余-70Thread-1取出90Thread-1剩余-70 這里是模擬的從賬戶取錢的操作,是用的同步方法,但是這里鎖失敗了。我看別人說是account沒鎖住,但是account也是person對象的成員啊,同步方法不是把person對象鎖住了嗎,為什么這里沒上鎖呢?
查看完整描述

2 回答

?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

已經解決了,每個對象都有一個監視器查看是否上鎖,person對象有,account對象也有,person對象上鎖并不能影響到account的鎖,這也就是為什么account沒被鎖住的原因,p1進入方法后,p2再進入是查看account的監視器,沒有鎖,成功進入。所以說沒有鎖住。這里需要的是account的鎖。

public void run() {    
        synchronized(account) {
        if (account.total-reduce<0) return ;
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        account.total-=reduce;
        System.out.println(Thread.currentThread().getName()+"取出"+reduce);
        System.out.println(Thread.currentThread().getName()+"剩余"+account.total);
        
        }
    }
查看完整回答
反對 回復 2019-02-12
?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

p1,p2是兩個不同的線程對象,他們進入同步方法run()的時候分別拿的是p1, p2各自的鎖,所以他們根本沒起到同步效果

查看完整回答
反對 回復 2019-02-12
  • 2 回答
  • 0 關注
  • 600 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號