关于存取钱和卖票系统的线程问题

这是刚学线程的时候,使用线程做的题目,关于存取钱以及卖票系统

两者都很简单,卖票系统代码如下

public class Testcode extends Thread{
	public Testcode(String name){
		super(name);
	}
	static int ticket=30;
	static Object ob="a";
	public void run(){
		while(ticket>0){
			synchronized(ob){
				if(ticket>0){
					System.out.println(getName()+"卖出了第"+ticket+"张票");
					ticket--;
				}
				else{
					System.out.println("票卖完了");
				}
			}
			try{
				sleep(1000);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) {
		Testcode st1=new Testcode("窗口1");
		Testcode st2=new Testcode("窗口2");
		st1.start();
		st2.start();
	}	
}

存取钱题目的主代码,使用synchronized是为了确保一次只有一个人进行操作

public class bank extends Thread{
	private static int money;

	public static int getm() {
		return money;
	}

	public void savemoney(int m) {
		synchronized (this) {
			money= m + money;
			System.out.println("存钱后为:" + money);
		}
	}

	public void getmoney(int m) {
		synchronized (this) {
			if (bank.getm()<= 0) {
				System.out.println("取钱失败,余额不足");
			} 
			else {
				money = money-m;
				System.out.println("取钱后为:" + money);
			}
		}
	}
	public static void main(String[] args) {
		cun c1=new cun();
		cun c2=new cun();
		qu q1=new qu();
		qu q2=new qu();
		c1.start();
		c2.start();
		q1.start();
		q2.start();
	}

}

接下来的代码是存取钱的代码,都很简单

public class qu extends Thread{
	private bank bank=new bank();
	public void run(){
		int m=100;
		int i=0;
		while(i<5){
			bank.getmoney(m);
		try{Thread.sleep(100);
		}catch(InterruptedException e){
			e.printStackTrace();
		}
		i++;
		}
	}
}
public class cun extends Thread {
	private bank bank=new bank();
	public void run(){
		int m=100;
		int i=0;
		while(i<5){
			bank.savemoney(m);
			i++;
		try{Thread.sleep(100);
		}catch(InterruptedException e){
			e.printStackTrace();
		}}
	}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值