java 解决线程安全的两种方式(Synchornized和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();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~