张三和妻子各拥有一张银行卡和存折,可以对同一个银行账户进行存取款的操作,请使用多线程及同步方法模拟张三和妻子同时取款的过程。需求说明:要求使用同步方法和同步代码块两种方式实现。
代码:
Bank.java
package duo;
public class Bank implements Runnable {
int money = 5000;
@Override public void run() {
while (true) { if (money == 0) { break;
} sale();
}
}
public synchronized void sale() { if (money > 0) {
System.out.println(Thread.currentThread().getName() + "准备取款...");
System.out.println(Thread.currentThread().getName() + "取款完毕!");
money -= 100; try {
Thread.sleep(500);
} catch (Exception e) {
}
} else { for (int i = 0; i < 5; i++) {
System.out.println("余额不足以支付" + Thread.currentThread().getName() +
"的取款,余额为 0");
}
}
}
private int money1 = 500; // 存款 500 private int num = 0; // 存款不足的次数
public void run1() {
for (int i = 0; i < 5; i++) { // 取款 5 次
synchronized (this) { int num = 0;
if (num >= 5) { break;
}
if (money1 > 0) { // 存款够的时候
System.out.println(Thread.currentThread().getName() + "准备取款");
System.out.println(Thread.currentThread().getName() + "完成取款");
} else if (money1 <= 0) { // 存款不足时 num++;
System.out.println(" 余 额 不 足 以 支 付 " +
Thread.currentThread().getName() + "的取款,余额为 0");
}
money1 -= 100; try { Thread.sleep(500); // 模拟取款时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Test1.java
package duo;
public class Test {
public static void main(String[] args) {
Bank bank =new Bank();
Thread thread=new Thread( bank,"张三" );
Thread thread1=new Thread( bank,"张三的妻子" );
thread.start();
thread1.start();
}
}
网友评论