class="java">package com.lj.thread7;
public class FetchMoney
{
public static void main(String[] args)
{
Bank bank=new Bank();
Thread t1=new Thread(new MoneyThread(bank),"t1");
Thread t2=new Thread(new MoneyThread(bank),"t2");
t1.start();
t2.start();
//System.out.println(bank.getMoney());
}
}
class Bank{
private static Integer money=1000;
public int getMoney(){
return this.money;
}
public void changeMoney(int number) throws InterruptedException{
[b]synchronized [/b](money)
{
Thread.sleep(5000);
money+=number;
}
System.out.println("money= "+money);
}
public [b]synchronized [/b]int getMoney(int number) throws InterruptedException{
if(number<0){
return -1;
}
else if(number >money){
return -2;
}
else{
//模拟一下取款所用的时间
Thread.sleep(3000);
money-=number;
System.out.println("money= "+money+" by "+Thread.currentThread().getName());
return number;
}
}
}
class MoneyThread implements Runnable{
private Bank bank;
public MoneyThread(Bank bank)
{
this.bank = bank;
}
@Override
public void run()
{
try
{
//System.out.println(bank.getMoney(800));
bank.changeMoney(500);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这里分别用synchronized锁定了方法和变量对象。
两种方法都可以实现对对象的锁定, 然后让不同的
线程有先后顺序的访问。
//等待编辑