一、模拟一个账号在银行取钱,里面有固定的余额100元,开多个线程来取钱,保证不能将钱取成负值
帐号类:
线程类:
测试类:
效果图:
二、模拟一次烧水的过程,从0度到100度,水开之后停止加热
帐号类:
public class Account {
public static int allMoney = 100;
//对一个方法进行加锁
//synchronized作用: 如果这个方法有一个线程在走时,其他线程就进不来。
//它一定是等一个线程把这方法全部走完之后,才会让另外一个线程进来
public synchronized static void getBankMoney(int money) {
System.out.println("取款:" + money);
if ((allMoney - money) <= 0) {
System.out.println("余额不足");
} else {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
allMoney -= money;
System.out.println("余额是:" + allMoney);
}
}
}
线程类:
public class GetMoneyThread implements Runnable {
private int money;
public GetMoneyThread(int money) {
this.money = money;
}
public void run() {
Account.getBankMoney(money);
}
}
测试类:
public class Test {
public static void main(String[] args) {
new Thread(new GetMoneyThread(55)).start();
new Thread(new GetMoneyThread(55)).start();
}
}
效果图:
二、模拟一次烧水的过程,从0度到100度,水开之后停止加热
import java.util.Timer;
import java.util.TimerTask;
public class HeatWater {
private static int i = 0;// 起始水温0度
public static void main(String[] args) {
final Timer timer = new Timer();
// 第一个参数是TimerTask,第二个参数是延迟,第三个参数是间隔时间
timer.schedule(new TimerTask() {
@Override
public void run() {
if (i <= 100) {
System.out.println("正在加热中...\t当前温度" + i + "度");
i += 5; // 5度一加
if (i > 100)
System.out.println("水开了!!!");
} else {
timer.cancel();// 定时器停止
}
}
}, 0, 1000);
}
}