Java多线程 模拟 购买 退订 机票

 

 

 Java多线程 模拟 购买 退订 机票

 

 

 

 

package cn.com.cloud.sea.thread;
/**
 * @author HenryLee
 * @version 1.0
 * 买票
 */
public class BuyTicketThread implements Runnable{
	/**
	 * 购票数量 default:num = 1
	 */
	public int num = 1;
	public void run() {
		sore();
	}
	public void sore()
	{
		synchronized (Ticket.class) {//这里线程同步,保证NumTemp被该线程锁住
			for (int i = 0; i < num; i++) {
				System.out.println(this.getClass()+"第"+i+"个买票。"+"买票:我要买一张票,正在拿票.....原总票数:"+Ticket.getNum()+"张......");
				
				Ticket.minusNum();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(this.getClass()+"第"+i+"个买票。"+"买票:我买到了一张票,总票数剩下:"+Ticket.getNum()+"张!");
			}
		}
	}
}


 

 

 

 

package cn.com.cloud.sea.thread;
/**
 * @author HenryLee
 * @version 1.0
 * 退票
 */
public class RefundTicketThread implements Runnable{
	/**
	 * 购票数量 default:num = 1
	 */
	public int num = 1;
	public void run() {
		sore();
	}
	public void sore()
	{
		synchronized (Ticket.class) {//这里线程同步,保证NumTemp被该线程锁住
			for (int i = 0; i < num; i++) {
				System.out.println(this.getClass()+"第"+i+"个退票。"+"退票:我要退一张票,正在办理退票手续.....原总票数:"+Ticket.getNum()+"张........");
				Ticket.addNum();
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(this.getClass()+"第"+i+"个退票。"+"退票:我成功退了一张票,总票数剩下:"+Ticket.getNum()+"张!");
			}
		}
	}
}


 

 

 

package cn.com.cloud.sea.thread;
/**
 * @author HenryLee
 * @version 1.0
 * 机票
 */
public class Ticket {
	/**
	 * 机票数
	 */
	private static int num = 10;
	
	/**
	 * 增加机票数量,返回增加后的总票数量
	 * @return
	 */
	public static int addNum()
	{
		num = num+1;
		return num;
	}
	/**
	 * 减少机票数量,返回减少后的总票数量 
	 * @return
	 */
	public static int minusNum()
	{
		num=num-1;
		return num;
	}
	public static int getNum() {
		return num;
	}
	public static void setNum(int num) {
		Ticket.num = num;
	}
}


 

 

 

package cn.com.cloud.sea.thread;
/**
 * @author HenryLee
 * @version 1.0
 * 客户端
 */
public class Client {
	public static void main(String[] args) {
		BuyTicketThread buy1=new BuyTicketThread();
		buy1.num=2;//购买两张机票
		RefundTicketThread refund1=new RefundTicketThread();
		refund1.num=1;
		
		Thread buy1Thread = new Thread(buy1);
		Thread refund1Thread = new Thread(refund1);
		
		buy1Thread.start();
		refund1Thread.start();
	}
}


 

 

 

 

 

 

最终运行的结果如下:

 

class cn.com.cloud.sea.thread.BuyTicketThread第0个买票。买票:我要买一张票,正在拿票.....原总票数:10张......
class cn.com.cloud.sea.thread.BuyTicketThread第0个买票。买票:我买到了一张票,总票数剩下:9张!
class cn.com.cloud.sea.thread.BuyTicketThread第1个买票。买票:我要买一张票,正在拿票.....原总票数:9张......
class cn.com.cloud.sea.thread.BuyTicketThread第1个买票。买票:我买到了一张票,总票数剩下:8张!
class cn.com.cloud.sea.thread.RefundTicketThread第0个退票。退票:我要退一张票,正在办理退票手续.....原总票数:8张........
class cn.com.cloud.sea.thread.RefundTicketThread第0个退票。退票:我成功退了一张票,总票数剩下:9张!

 

 


 

阅读更多
个人分类: Java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭