- package cn.itcast.demo;
- import java.lang.Thread.State;
- public class Test {
- /**
- *
- * 毕老师基础视频11天11.
- *
- *需求:银行有一个金库。
- *
- *有两个储户分别存300元,每次存100,存3次。
- */
- public static void main(String[] args) {
- Cus c = new Cus();
- Thread t1 = new Thread(c);// 两个储户同时向银行存储。
- Thread t2 = new Thread(c);
- t1.start();
- t2.start();
- }
- }
- class Bank
- {
- private int sum;// 此处的sum相当与银行的总存款。
- private int x,y;
- Object obj = new Object();
- public void add(int n) {
- synchronized (obj)
- {
- sum = sum + n;
- String str = Thread.currentThread().getName();
- if(str.equals("Thread-0"))
- {
- try {
- x = x + n;
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- System.out.println(Thread.currentThread().getName()+"存款:"+x+";"+"银行总余额:" + sum);
- }
- else
- {
- if(str.equals("Thread-1"))
- {
-
- try {
- y = y + n;
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- System.out.println(Thread.currentThread().getName()+"存款:"+y+";"+"银行总余额:" + sum);
- }
- }
- }
- }
- }
- class Cus implements Runnable// 储户类?
- {
- Bank b = new Bank();
- public void run()
- {
- for (int i = 0; i < 3; i++) {
- b.add(100);
-
- }
- }
- }
复制代码 |
|