java中的每一个对象都有一个内部锁,并且是嵌入到java语言内部的机制—Synchronized。米一个对象都有一个内部锁,并且该锁又一个内部条件。由锁来管理那些试图进入synchronized方法的线程,由条件来管理那些调用wait的线程。内部锁只有一个相关条件。wait方法添加一个线程到等待集中,notifyAII /notify方法解除等待线程的阻塞状态。package test3;public class Bank { PRivate final double[] accounts; public Bank(int n, double initialBance) { accounts = new double[n]; for (int i = 0; i < accounts.length; i++) { accounts[i] = initialBance; } } public synchronized void transfer(int from, int to, double amount) throws InterruptedException { while (accounts[from] < amount) { /*将改线程放入阻塞集中*/ wait(); } System.out.println(Thread.currentThread()); accounts[from] -= amount; System.out.printf("%10.2f from %d to %d ", amount, from, to); accounts[to] +=amount; System.out.printf("Total Blance: %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; }}package test3;public class TransferRunnable implements Runnable{ private Bank bank; private int fromAccount; private double maxAmount; private int DELAY = 10; public TransferRunnable(Bank bank, int fromAccount, double maxAmount) { this.bank = bank; this.fromAccount = fromAccount; this.maxAmount = maxAmount; } @Override public void run() { try { while (true) { int toAccount = (int) (bank.size() * Math.random()); double amount =maxAmount * Math.random(); bank.transfer(fromAccount, toAccount, amount); Thread.sleep((int) ((DELAY) * Math.random())); } } catch (Exception e) { e.printStackTrace(); } }}package test3;public class UnsynchBankTest { public static final int NACCOUNTS = 100; public static final double INITIAL_BALANCE = 1000; public static void main(String[] args) { Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE); for (int i = 0; i < NACCOUNTS; i++) { TransferRunnable r = new TransferRunnable(b, i, INITIAL_BALANCE); Thread t = new Thread(r); t.start(); } }}