java 解决线程安全的两种方式(Synchornized和Lock)
原文链接:https://www.cnblogs.com/MrFugui/p/15610780.html
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();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2021-08-01 $(document).ready和window.onload区别
2021-08-01 为什么script标签一般放在body下面
2021-08-01 idea添加jar和移除jar包的三种方式
2021-08-01 HTML转义字符大全(转)
2021-08-01 C#中 以固定长度 取字符串中的数据
2021-08-01 Oracle的substr函数简单用法和 C#中一样
2021-08-01 ORA-22835:缓冲区对于CLOB到CHAR转换而言太小