java线程同步--同步代码块

//package hl.crja.toob.multhread;

/**
 * 同步监视器 : 使用 synchronized 修饰的 对象
 * 同步代码块 : 使用 synchronized 修饰的 代码块
 * 同步方法   : 使用 synchronized 修饰的 方法
 *
 * eg :
 * synchronized (obj) // obj 为 同步监视器
 * {
 *     ...// 此处为 同步代码块
 * }
 * public synchronized void test(String aaa) // 此方法为 同步方法
 * {
 *     System.out.println(aaa);
 * }
 *
 * @author Liu Huan
 */

/**
 * 账户类:包含 账户id  和  账户余额
 */
public class Account {
    private String id;
    private int balance;

    public Account(String id,int balance){
        this.id = id;
        this.balance = balance;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

    public int getBalance() {
        return balance;
    }
}

/**
 * 取钱线程
 * acc 接收 传进来的 账户对象的引用
 * drawAmount  要取的 钱的总量
 */
class DrawMoney extends Thread {

    private Account acc;
    private int drawAmount;
    // 取钱线程的名字  取钱的账户  取钱的总量
    public DrawMoney(String name, Account acc, int drawAmount){
        super(name);
        this.acc = acc;
        this.drawAmount = drawAmount;
    }

    @Override
    public void run() {
        //synchronized (acc) {  // 是否使用 同步监视器
            if (acc.getBalance()>drawAmount){
                System.out.println(getName() + "取钱成功" + "金额:" + drawAmount);
                acc.setBalance(acc.getBalance()-drawAmount);
                System.out.println(getName() + "取后,账户余额:" + acc.getBalance());
            } else {
                System.out.println(getName() + "取钱失败");
            }
        //}
    }
}

class DrawTest {
    public static void main(String[] args) throws InterruptedException {
        var acct = new Account("1234",1000);
        var p = new DrawMoney("甲", acct, 800);
        p.start();

        var pp = new DrawMoney("乙", acct, 800);
        pp.start();

        var ppp = new DrawMoney("丙", acct, 800);
        ppp.start();
    }
}

不使用 同步代码块,运行结果:

开启同步代码块,结果:

 
 
 
 
 
 
 
 
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值