Java Simulated Cinema Ticket Sales and Refund

Java multithreading to solve the problem of ticket sales and refund

Using the multi-threading capability of the java language, write a program that simulates ticket selling and refunding in 4 windows. The functional requirements are as follows:
1) It can sell tickets at three windows at the same time (only responsible for ticket sales, not refunds), and all windows are sold. Ticket numbers cannot conflict.
2) The remaining fourth window is only responsible for refunds, and can randomly refund a certain ticket that has been sold (tickets that have been refunded and have not been sold again cannot be refunded), this window can be refunded at most 5 tickets
3) The returned tickets can still be sold
4) The function of each window is realized by a thread, and each time a ticket is sold or returned, it will sleep for 1000 milliseconds.
5) Each window is sold and returned The ticket number should be displayed on the screen to easily understand which ticket is sold or refunded from which window
6) The valid ticket number that can be sold is 1…100

class TicketThread implements Runnable {
    
    
	
	private int flag = 1;
	private int tickets = 100;
	Object obj = new Object();
	
	@Override
	public void run() {
    
    
		while(true) {
    
    
			try {
    
    
				SaleTickets();
			} catch (InterruptedException e) {
    
    
				e.printStackTrace();
			}
		}
	}
	
public synchronized void SaleTickets() throws InterruptedException {
    
    
		if(tickets > 0) {
    
    
			if(Thread.currentThread().getName().equals("窗口4") && Math.random() > 0.5 && tickets < 100) {
    
    
				tickets++;flag ++;
				System.out.println("窗口4退票第" + tickets + "张票");
				if(flag > 5) {
    
        //此窗口累计最多能退回5张票
					this.wait();  //退票完成后,让此线程休眠
				}
			}else {
    
    
				System.out.println(Thread.currentThread().getName()+ "正在售卖第" + tickets + "张票");
				tickets--;
			}
			Thread.sleep(1000);
		}
	}
}

public class Tickets {
    
    
	public static void main(String[] args) {
    
    
		//创建线程对象
		
		TicketThread tt = new TicketThread();
		Thread t = new Thread(tt);
		t.setName("窗口1");
		Thread t2 = new Thread(tt);
		t2.setName("窗口2");
		Thread t3 = new Thread(tt);
		t3.setName("窗口3");
		Thread t4 = new Thread(tt);
		t4.setName("窗口4");
		
		//启动线程对象
		t.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

The following is the execution result
Insert picture description here

Guess you like

Origin blog.csdn.net/Lovely_Xiaoguo/article/details/108735211