多线程售票实现

前两天写了个多线程售票的程序,练习下多线程和同步的概念,把代码贴出来与大家分享!

package test.thread;

class Test implements Runnable {//多线程售票类
	station s=new station();
	
	public static void main(String[] args) {
		Test test = new Test();
		Thread t1 = new Thread(test);
		Thread t2 = new Thread(test);
		Thread t3 = new Thread(test);
		
		t1.setName("t1"); 
		t2.setName("t2");
		t3.setName("t3");
		t1.start(); 
		t2.start();
		t3.start();
	}
  
	public void run(){
		while(s.getTicket()>0){s.sellTicket(Thread.currentThread().getName());
	}
}

 

package test.thread;

public class station {//车站类
	 private static station instance = null;
	 private static int ticket=100;
	 public static synchronized station getInstance(){
		 if(instance == null)   
	        instance = new station();   
	        return instance;   
	} 
	 
	public synchronized void sellTicket(String threadName){
		if(ticket>0){
			System.out.println("线程 "+threadName+"得到票 "+ticket);
			ticket--;
		}
	}

	public static int getTicket() {
		return ticket;
	}

	public static void setTicket(int ticket) {
		station.ticket = ticket;
	}
	
}

 上面的代码中车站类不必写成单例形式,分析下run方法体中的多线程代码,其中写一个车站卖票的方法,卖票方法中有2个动作,第一步得到票,第二步票数减1,这两个动作不能被多线程打断,所以要放在同步方法体中,在run方法体中s.getTicket()不是同步的方法,就是说可以有多个线程一起执行这个方法,得到当前票数是100,但只有一个线程能够进入到售票的方法中进行售票,然后票数减1,而其他线程进入到售票的方法中,看到的车票是减1后的票数,保持了数据一致,不会出现同一张票卖多次的情况,直至把票卖完!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值