帳號類:
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);
}
}