package com.itheima.day19;
public class Demo04 {
public static void main(String[] args) {
/*、模拟两个人向银行存钱,每次存300,两个人总共存十次*/
MyRunnable tr = new MyRunnable();
new Thread(tr,"张三").start();
new Thread(tr,"李四").start();
}
}
class MyRunnable implements Runnable{
private int money = 300; //一次存多少钱
private int num = 10;// 存了多少次 1-10
private int sum; //一共存了多少钱
public void run() {
//哪个线程进来
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while(true){
synchronized (this) {
String name = Thread.currentThread().getName();
if(num < 1){
//什么情况退出
break;
}
num--;
sum += money; // 求出一共有多少钱
System.out.println(name + "存入了"+money+"此时银行一共有"+(sum));
}
}
}
}
|
|