小练习 ---- 简单的多线程模拟

一、模拟一个账号在银行取钱,里面有固定的余额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);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值