java多线程简单项目--电影院售票机

看了网上那么多资料和视频,大概也知道线程的API怎么用了,那就做一个项目来检测一下知识吧~~

下面这个是测试类,用于设定参数和开始线程,没什么好说的。(知识点:创建线程对象,线程开启)

 

package com.thread.movticket;
* 电影票系统线程测试
 * 使用方法:sleep,synchronic,join,wait,notify,start,setpriority,yield
 * 业务功能:
 * vip购票通道购票,平民购票(join,wait,notify)
 */
public class MovieTest {
    public static void main(String[] args){
    	//电影票数
    	int ticketAmount = 1000;
    	//根据票数创建电影售票系统
    	MovieSystem movieSystem = new MovieSystem(ticketAmount);
    	try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
    	
    	//开启三个窗口买票,两个平民,一个vip
    	SaleTicket saleTicketA =new SaleTicket(movieSystem,0,ticketAmount);//电影系统对象,vip等级,票数
    	SaleTicket saleTicketB =new SaleTicket(movieSystem,0,ticketAmount);
    	SaleTicket vipSaleTicket = new SaleTicket(movieSystem,1,ticketAmount);
    	System.out.println("******鹅厂电影院开业*****");
    	
    	Thread t1 = new Thread(saleTicketA,"窗口A");
    	Thread t2 = new Thread(saleTicketA,"窗口B");
    	Thread t3 = new Thread(saleTicketA,"Vip窗口");

    	t1.start();
    	t2.start();
    	t3.start();
    }
}

 

下面是主类(知识点:sleep())

 

package com.thread.movticket;

public class MovieSystem {
	
	//电影票.电影票总数
	private int ticketAmount;
	private int[] ticket;
	
	public MovieSystem(int ticketAmount) {
		
		//实例化票数创建数组
		this.ticketAmount = ticketAmount;
		ticket = new int[ticketAmount];
		
		//给电影票以座位号划分()
		for (int i=0;i0) {
			if (ticket[ticketAmount-1] > 0) {
			ticketAmount--;
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return ticketAmount+1;
			}
			}
			return -1;//没票
	}
}

然后是线程类(知识点:①keepRunning停止线程②setPriority()设置线程优先级③synchronize(object o)线程的同步锁,个人感觉对象o没什么用,写上就可以了

 

package com.thread.movticket;

public class SaleTicket extends Thread{
	
	//共享电影系统,创建锁对象,创建显性对象
	private MovieSystem movieSystem;	
	Object object = new Object();
	boolean KeepRunning = true;
//	private int ticketAmount;
//	int[] seat ;
	
	//共享电影院系统和票数,设置vip等级
	public SaleTicket(MovieSystem movieSystem,int viplever,int ticketAmount) {
		
		this.movieSystem = movieSystem;
		
		//根据vip等级设置快慢,目前只有普通和vip1级
		if (viplever == 0) {
			Thread.currentThread().setPriority(MIN_PRIORITY);
		}else if (viplever == 1) {
			Thread.currentThread().setPriority(MAX_PRIORITY);
		}
	}
	
	public void run() {
		
		while(KeepRunning){			
			//储存电影系统返回的电影票数量(座位号)并且用synchronize防止被多个线程读取同一个座位号
			int num;
			synchronized(object){
				num = movieSystem.saleTicket();
			if (num > 0) {
				System.out.println(Thread.currentThread().getName()+":卖出"+num+"号座位");
				System.out.println("还剩"+(num-1)+"张票");
			}else if (num == -1) {
				System.out.println(Thread.currentThread().getName()+"."+"没票了~~");
				KeepRunning = false;
			}
			}
		}
	}
}

基本就这些吧~~涉及的知识太浅薄了,羞愧。

 

 

你可能感兴趣的:(Java)