模拟两个线程同时取钱的过程,使用同步代码块防止多取
- package com.hspedu;
-
- /**
- * @author: guorui fu
- * @versiion: 1.0
- */
- public class Homework02 {
- public static void main(String[] args) {
- Withdraw withdraw = new Withdraw();
- Thread thread1 = new Thread(withdraw);
- thread1.setName("t1");
- Thread thread2 = new Thread(withdraw);
- thread2.setName("t2");
- thread2.start();
- thread1.start();
- }
- }
-
- class Withdraw implements Runnable {
- private int sum = 10000;
-
- @Override
- public void run() {
-
- while (true) {
- synchronized (this) {
- if (sum <= 0) {
-
- System.out.println(Thread.currentThread().getName() + " 尝试取钱,但余额不足。。。");
- break;
- }
-
- sum -= 1000;
- System.out.println(Thread.currentThread().getName() + "取出1000,余额:" + sum);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-
- }
- }