Java多线程 模拟售票窗口售票

编写一个Java 多线程程序,完成三个售票窗口同时出售20张票

程序分析:

1.票数要使用同一个静态值;
2.为保证不会出现卖出同一个票数,要java多线程同步锁。
设计思路:
创建一个站台类Station,继承Thread,重写run方法,在run方法里面执行售票操作!售票要使用同步锁:即有一个站台卖这张票时,其他站台要等这张票卖完!
2.创建主方法调用类

方法1:同步方法

public class Safe01 extends Thread{

	private int num = 30;
	boolean flag = true;
	
	@Override
	public  void run() {
		while(flag) {
			sale();
			try {
				Thread.sleep(100);
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	//synchronized 锁的是this(也就是对象)的资源,而不是方法。
	private synchronized void sale() {
		
		if(num > 0) {
			try {
                Thread.sleep(100);
                } catch(Exception e) {

                }
			System.out.println(Thread.currentThread().getName()+"卖出了第"+num--+"张票");
		}else {
			System.out.println("票卖完了");
			flag = false;
			return;
		}
	}
		
	
	public static void main(String[] args) {
		 Safe01 sell = new Safe01();
		 Thread sell1 = new Thread(sell, "窗口1");
		 Thread sell2 = new Thread(sell, "窗口2"); 
		 Thread sell3 = new Thread(sell, "窗口3"); 
		 sell1.start(); 
		 sell2.start(); 
		 sell3.start();
		 
	}
}


方法2:同步块

import java.util.Date;

public class Safe03 extends Thread{

	private int num = 300;
	boolean flag = true;
	
	@Override
	public  void run() {
		while(flag) {
			if(num <= 0) {
				return;
			}
			synchronized((Integer)num) {
				if(num > 0) {
					
					System.out.println(Thread.currentThread().getName()+"卖出了第"+num--+"张票");
				}else {
					System.out.println("票卖完了");
					flag = false;
					return;
				}
				try {
					Thread.sleep(100);
				}catch(InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		 Safe03 sell = new Safe03();
		 Thread sell1 = new Thread(sell, "窗口1");
		 Thread sell2 = new Thread(sell, "窗口2"); 
		 Thread sell3 = new Thread(sell, "窗口3"); 
		 sell1.start(); 
		 sell2.start(); 
		 sell3.start();
		 
	}
}

  • 写的时候要注意 共享的变量尽量不要暴露在没加同步锁的地方
  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值