java 解决线程安全的两种方式(Synchornized和Lock)

本文通过两个示例对比了synchronized与Lock两种线程同步机制。synchronized关键字会在执行完同步代码后自动释放锁,而Lock则需要手动加锁与解锁。通过具体的银行账户存款操作演示了这两种机制的实现方式。

synchornized与lock的不同:

synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器

lock需要手动的启动同步(Lock()),同时结束同步也需要使用手动的实现(unlock())

synchornized方法实现线程同步方法:

public class ThreadBankTest {
    public static void main(String[] args) {
        Account account = new Account(0);
        Customer customer = new Customer(account);
        Customer customer2 = new Customer(account);
        customer.setName("甲");
        customer2.setName("乙");
        customer.start();
        customer2.start();
    }
}

class Customer extends Thread {
    private Account account;


    public Customer(Account account) {
        this.account = account;

    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {

            account.deposit(1000);
        }
    }
}
class Account {
    private int balance;

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

    //存钱
    public synchronized void deposit(int money) {
        if (money > 0) {
            balance += money;
            System.out.println(Thread.currentThread().getName()+"存钱成功"+balance);

        }
    }
}

Lock实现线程同步的方法:

public class ThreadBankTest2 {
    public static void main(String[] args) {
        Account2 account2 = new Account2(0);
        Customer2 customer = new Customer2(account2);
        Customer2 customer2 = new Customer2(account2);
        customer.setName("甲");
        customer2.setName("乙");
        customer.start();
        customer2.start();
    }
}

class Customer2 extends Thread {
    private Account2 account;


    public Customer2(Account2 account) {
        this.account = account;

    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            account.deposit(1000);
        }
    }
}

class Account2 {
    private int balance;
    //1.实例化ReentrantLock
    private ReentrantLock lock = new ReentrantLock();

    public Account2(int balance) {
        this.balance = balance;
    }

    //存钱
    public void deposit(int money) {
        try {
            //2.调用lock方法:要把要同步的代码放入到try中,try后面的代码就是要实现同步代码
            lock.lock();
            if (money > 0) {
                balance += money;
                System.out.println(Thread.currentThread().getName()+"存钱成功"+balance);

            }
        } finally {
            //3.给lock解锁unlock
            lock.unlock();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

掉头发的王富贵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值