1package synch;
2 3import java.util.*;
4import java.util.concurrent.locks.*;
5 6/** 7 * A bank with a number of bank accounts that uses locks for serializing access.
8 * @version 1.30 2004-08-01
9 * @author Cay Horstmann
10*/11publicclass Bank
12{
13privatefinaldouble[] accounts;
14/**与同步控制有关的类对象*/15private Lock bankLock; //lock对象16private Condition sufficientFunds;//condition对象 1718/**19 * Constructs the bank.
20 * @param n the number of accounts
21 * @param initialBalance the initial balance for each account
22*/23public Bank(int n, double initialBalance)
24 {
25 accounts = newdouble[n];
26 Arrays.fill(accounts, initialBalance); //数组account的填充27 bankLock = new ReentrantLock();
28 sufficientFunds = bankLock.newCondition();
29 }
3031/**32 * Transfers money from one account to another.
33 * @param from the account to transfer from
34 * @param to the account to transfer to
35 * @param amount the amount to transfer
36*/37publicvoid transfer(int from, int to, double amount) throws InterruptedException //模拟行内转账操作38 {
39 bankLock.lock(); //加锁操作40try41 {
42while (accounts[from] < amount)
43 sufficientFunds.await(); //阻塞事件队列44 System.out.print(Thread.currentThread());
45 accounts[from] -= amount;
46 System.out.printf(" %10.2f from %d to %d", amount, from, to);
47 accounts[to] += amount;
48 System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
49 sufficientFunds.signalAll();//唤醒所有线程50 }
51finally52 {
53 bankLock.unlock(); //解除锁操作54 }
55 }
5657/**58 * Gets the sum of all account balances.
59 * @return the total balance
60*/61publicdouble getTotalBalance()
62 {
63 bankLock.lock();
64try65 {
66double sum = 0;
6768for (double a : accounts)
69 sum += a;
7071return sum;
72 }
73finally74 {
75 bankLock.unlock();
76 }
77 }
7879/**80 * Gets the number of accounts in the bank.
81 * @return the number of accounts
82*/83publicint size()
84 {
85return accounts.length;
86 }
87 }
package synch;
/**
* This program shows how multiple threads can safely access a data structure.
* @version 1.31 2015-06-21
* @author Cay Horstmann
*/publicclass SynchBankTest
{
publicstaticfinalint NACCOUNTS = 100;
publicstaticfinaldouble INITIAL_BALANCE = 1000;
publicstaticfinaldouble MAX_AMOUNT = 1000;
publicstaticfinalint DELAY = 10;
publicstaticvoid main(String[] args)
{
Bank bank = new Bank(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 t = new Thread(r);
t.start();
}
}
}
运行截图:
测试程序2:
l 在Elipse环境下调试教材655页程序14-8,结合程序运行结果理解程序;
l 掌握synchronized在多线程同步中的应用。
package synch2;
import java.util.*;
/**
* A bank with a number of bank accounts that uses synchronization primitives.
* @version 1.30 2004-08-01
* @author Cay Horstmann
*/publicclass Bank
{
privatefinaldouble[] accounts;
/**
* Constructs the bank.
* @param n the number of accounts
* @param initialBalance the initial balance for each account
*/public Bank(int n, double initialBalance)
{
accounts = newdouble[n];
Arrays.fill(accounts, initialBalance);
}
/**
* Transfers money from one account to another.
* @param from the account to transfer from
* @param to the account to transfer to
* @param amount the amount to transfer
*/publicsynchronizedvoid transfer(int from, int to, double amount) throws InterruptedException//sysynchronized关键字修饰方法实现加锁操作 {
while (accounts[from] < amount)
wait(); //wait()方法导致线程进入等待状态直到它被通知,该方法只能在一个同步方法中调用
System.out.print(Thread.currentThread());//Thread.currentThread()返回当前执行线程的Thread对象
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(); //解除那些在该对象上调用wait方法的线程的阻塞状态 }
/**
* Gets the sum of all account balances.
* @return the total balance
*/publicsynchronizeddouble getTotalBalance()
{
double sum = 0;
for (double a : accounts)
sum += a;
return sum;
}
/**
* Gets the number of accounts in the bank.
* @return the number of accounts
*/publicint size()
{
return accounts.length;
}
}
package synch2;
/**
* This program shows how multiple threads can safely access a data structure,
* using synchronized methods.
* @version 1.31 2015-06-21
* @author Cay Horstmann
*/publicclass SynchBankTest2
{
publicstaticfinalint NACCOUNTS = 100;
publicstaticfinaldouble INITIAL_BALANCE = 1000;
publicstaticfinaldouble MAX_AMOUNT = 1000;
publicstaticfinalint DELAY = 10;
publicstaticvoid main(String[] args)
{
Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
for (int i = 0; i < NACCOUNTS; i++)
{
int fromAccount = i;
/**lamber表达式*//*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)
{
}
};*//**直接声明
* Runnable r=new Runnable() {
@Override
public void run() {
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 t = new Thread(new Runnable(){
@Override
publicvoid run() {
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)
{
}
};
});
t.start();
}
}
}