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();
}
}
}
标签:account,java,int,Lock,Synchornized,lock,new,balance,public
From: https://www.cnblogs.com/sunny3158/p/17598796.html