Java多线程-模拟售票

使用Synchronize同步ticket对象,注意同步代码块要在while循环里面写。不然就会出现只有一个线程把票买完的情况。

Customer接口:

package 卖票;

@FunctionalInterface
public interface Customer {
	void buyTicket();
}


Ticket类:

package 卖票;

/**
 * 票
 * @author Z7M-SL7D2
 *
 */
public class Ticket {
	Integer ticketCount;

	public Integer getTicketCount() {
		return ticketCount;
	}

	public void setTicketCount(Integer ticketCount) {
		this.ticketCount = ticketCount;
	}

	public Ticket(Integer ticketCount) {
		super();
		this.ticketCount = ticketCount;
	}
}


测试类:

package 卖票;

public class Test {
	public static void main(String[] args) {
		Ticket ticket = new Ticket(1000);

		Customer buy = ()-> {
			ticket.ticketCount--;
		};

		Runnable buyAction = ()-> {
			while (true) {
				synchronized (ticket) {
					if (ticket.getTicketCount() <= 0)
						return;
					buy.buyTicket();
					System.out.println(Thread.currentThread().getName() + "买去了一张,还剩下" + ticket.getTicketCount());
				}
			}
		};

		Thread customer1 = new Thread(buyAction, "消费者1");

		Thread customer2 = new Thread(buyAction, "消费者2");
		
		Thread customer3 = new Thread(buyAction, "消费者3");

		Thread customer4 = new Thread(buyAction, "消费者4");

		customer1.start();
		customer2.start();
		customer3.start();
		customer4.start();

	}
}


运行结果:



猜你喜欢

转载自blog.csdn.net/bugggget/article/details/80109971