Lock 和 Condition接口提供了高度的锁定控制,大多数情况下并不需要这样的控制; java中的每一个对象都有一个内部锁;如果一个方法用synchronized关键字进行声明,那么对象的内部锁将保护整个方法
public class UnsynchBankTest {
public static final int NACCOUNTS = 100;
public static final double INITIAL_BALANCE = 1000;
public static final double MAX_AMOUNT = 1000;
public static final int DELAY = 10;
public static void main(String[] args) {
Bank2 bank = new Bank2(NACCOUNTS, INITIAL_BALANCE);//创建一个银行对象;这个银行有一百个用户;一百个用户使用这个银行
for (int i = 0; i < NACCOUNTS; i++) {
int fromAccount = i;
Runnable r = () -> {
try
{
while (true) {
int toAccount = (int) (bank.size() * Math.random());//拿出一个随机账户
double amount = MAX_AMOUNT * Math.random();//设定随机一笔钱(支出/得到)
bank.transfer(fromAccount, toAccount, amount);//转账操作
Thread.sleep((int) (DELAY * Math.random()));//随机的休眠时间
}
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();//加上这句为好
}
};
Thread t = new Thread(r);//创建一个线程;该线程处于创建状态
t.start();//使线程处于可运行的状态(可能运行,也可能处于阻塞状态)
}
}
}
import java.util.Arrays;
public class Bank2 {
private final double[] accounts;
public Bank2(int n, double initialBalance) {
accounts = new double[n];
Arrays.fill(accounts, initialBalance);
}
public synchronized void transfer(int from, int to, double amount) throws InterruptedException {
while (accounts[from] < amount)
wait();//使线程处于等待集中
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf("%10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf("Total Balance: %10.2f%n", getTotalBalance());
notifyAll();//唤醒所有等待的线程
}
public synchronized double getTotalBalance() {
double sum = 0;
for (double a : accounts)
sum += a;
return sum;
}
public int size() {
return accounts.length;
}
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦