public class Bank implements Runnable {
int money = 100;
static Object obj = new Object();
static int count = 20;
/**
* @return the money
*/
public int getMoney() {
return money;
}
/**
* @param money
* the money to set
*/
public void setMoney(int money) {
this.money = money;
}
@Override
public void run() {
while (true) {
if (Thread.currentThread().getName().equals("用户A")) {
synchronized (obj) {
if (count < 1) {
break;
}
money+=100;
//this.setMoney(money+100);
System.out.println(Thread.currentThread().getName()
+ "线程正在执行第" + (21 - count) + "次,增加了100元,目前money的值为"
+ money + "元");
count--;
}
} else if (Thread.currentThread().getName().equals("用户B")) {
synchronized (obj) {
if (count < 1) {
break;
}
int x = (int) (Math.random() * 100) + 1;
System.out.println(Thread.currentThread().getName()
+ "线程正在执行第" + (21 - count) + "次,增加了" + x
+ "元,目前money的值为" + (money + x) + "元");
count--;
}
} else if (Thread.currentThread().getName().equals("用户C")) {
synchronized (obj) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (count < 1) {
break;
}
System.out.println(Thread.currentThread().getName()
+ "线程正在执行第" + (21 - count) + "次,睡眠了10毫秒");
count--;
}
}
}
}
}
public static void main(String[] args) {
Bank b = new Bank();
Thread t1 = new Thread(b,"用户A");
Thread t2 = new Thread(b,"用户B");
Thread t3 = new Thread(b,"用户C");
t1.start();
t2.start();
t3.start();
}
求高人指点
|
|