日期:2014-05-20 浏览次数:20989 次
package com.soko.quiz;
public class BankOperation
{
public static void main(String[] args) throws Exception
{
int[] addList = new int[]{100, 300, 800, 500, 400, 200, 600, 700};
int[] takeList = new int[]{300, 800, 500, 400, 100, 700, 600, 300};
Balance balance = new Balance();
Thread adder = new Adder(balance, addList);
Thread taker = new Taker(balance, takeList);
System.out.print("List:");
adder.start();
taker.start();
Thread.sleep(500);
System.out.println("\nBalance:" + balance.getMoney()); //正确答案是 -100
}
}
class Balance {
private int money = 0;
boolean isAddOver = false;
public synchronized int getMoney()
{
return this.money;
}
public synchronized void add(int num) throws Exception
{
this.notifyAll();
while((money + num) > 1000)
{
this.wait();
}
money += num;
System.out.print("add" + num + ", ");
System.out.println("balance:" + money);
}
public synchronized void take(int num) throws Exception
{
this.notifyAll();
while((money - num) < 100 && !isAddOver)
{
this.wait();
System.out.println("陷入循环无法跳出。 此时的money=" + money + "此时isAddOver=" + isAddOver);
}
money -= num;
System.out.print("take" + num + ", ");
System.out.println("balance:" + money);
}
}
class Adder extends Thread {
private Balance balance;
private int[] addList;
public Adder(Balance balance, int[] addList)
{
this.balance = balance;
this.addList = addList;
}
public void run()
{
for(int i=0; i<addList.length; i++)
{
try
{
balance.add(addList[i]);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Taker extends Thread {
private Balance balance;
private int[] takeList;
public Taker(Balance balance, int[] takeList)
{
this.balance = balance;
this.takeList = takeList;
}
public void run()
{
for(int i=0; i<takeList.length; i++)
{
try
{
balance.take(takeList[i]);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}