Java多线程售票问题

1、代码

public class Test {

	public static void main(String[] args) {
		
		Tickets tickets = new Tickets(10);
		new Thread(tickets, "售票员A").start();
		new Thread(tickets, "售票员B").start();
		new Thread(tickets, "售票员C").start();
	}
}
class Tickets implements Runnable {

	private int num;
	
	Tickets(int num) {
		
		this.num = num;
	}
	
	public void run() {
		
		while(num > 0) {
			
			sale();
		}
	}
	
	private synchronized void sale() {
		
        if(num > 0){  
        	
        	System.out.println(Thread.currentThread().getName() + "卖出一张火车票,还剩余"+ (--num) + "张票。");
        	try{  
                Thread.sleep(100);  
            }catch(InterruptedException e){  
                e.printStackTrace();  
            }  
        }  
    }  
}

2、运行结果

售票员A卖出一张火车票,还剩余9张票。
售票员A卖出一张火车票,还剩余8张票。
售票员B卖出一张火车票,还剩余7张票。
售票员C卖出一张火车票,还剩余6张票。
售票员C卖出一张火车票,还剩余5张票。
售票员B卖出一张火车票,还剩余4张票。
售票员B卖出一张火车票,还剩余3张票。
售票员A卖出一张火车票,还剩余2张票。
售票员A卖出一张火车票,还剩余1张票。
售票员A卖出一张火车票,还剩余0张票。
好的,我可以为您讲解一下Java多线程售票窗口的实现。假设有3个售票窗口,我们需要实现多线程售票系统,可以采用如下代码实现: ```java public class TicketSeller implements Runnable { private int tickets = 100; // 总票数为100张 @Override public void run() { while (true) { synchronized (this) { // 同步锁,确保多线程访问时线程安全 if (tickets > 0) { try { Thread.sleep(100); // 模拟售票需要的时间 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "售出第" + tickets + "张票"); tickets--; } else { break; } } } } } public class Main { public static void main(String[] args) { TicketSeller ticketSeller = new TicketSeller(); Thread thread1 = new Thread(ticketSeller, "售票窗口1"); Thread thread2 = new Thread(ticketSeller, "售票窗口2"); Thread thread3 = new Thread(ticketSeller, "售票窗口3"); thread1.start(); thread2.start(); thread3.start(); } } ``` 上述代码中,我们定义了一个实现了Runnable接口的TicketSeller类,该类中有一个tickets变量用于存储剩余票数。在run方法中,我们使用了synchronized关键字来确保多线程访问时线程安全,保证在同一时刻只有一个线程能够访问tickets变量。当tickets变量大于0时,线程会售出一张票,并将tickets变量减1,直到所有票都售出为止。 在Main类中,我们创建了3个线程来模拟3个售票窗口,分别调用TicketSeller类的run方法来实现售票。每个线程执行时都会调用run方法,同时访问tickets变量,通过synchronized同步锁来确保多线程访问时线程安全。 这样,我们就实现了一个简单的Java多线程售票窗口程序。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值