- public class GetMoney implements Runnable {
- private int money = 500; // 存款500
- private int num = 0; // 存款不足的次数
- @Override
- public void run() {
- // TODO Auto-generated method stub
- for (int i = 0; i < 5; i++) { // 取款5次
- synchronized (this) {
- if (num >= 5) {
- break;
- }
- if (money > 0) { // 存款够的时候
- System.out.println(Thread.currentThread().getName() + "准备取款");
- System.out.println(Thread.currentThread().getName() + "完成取款");
- System.out.println();
- } else if (money <= 0) { // 存款不足时
- num++;
- System.out.println("余额不足以支付" + Thread.currentThread().getName() + "的取款,余额为0");
- }
- money -= 100;
- try {
- Thread.sleep(500); // 模拟取款时间
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
- public class Test {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- GetMoney getMoney = new GetMoney();
- Thread thread = new Thread(getMoney,"张三");
- Thread thread1 = new Thread(getMoney,"张三的老婆");
- thread.start();
- thread1.start();
- }
- }
高级特性第4章2
最新推荐文章于 2024-02-20 16:16:31 发布