一、需求分析:
模拟卖票窗口,实现5个窗口同时卖100张票(代码为了截图采用30张票)
知识点:多线程,锁,多线程的安全问题,线程的生命周期
二、代码实现
public class TestSellTickets {
//此处也可采用普通的int
//static int count = 30;
static AtomicInteger count = new AtomicInteger(30);
static String[] windows = {
"窗口1","窗口2","窗口3","窗口4","窗口5"};
public static void main(String[] args) {
Thread[] threads = new Thread[5];
Object o =new Object();
for (int i=0;i<5;i++){
threads[i] = new Thread(() -> {
//采用lambda表达式创建线程,同时初始化给threads中的每个线程threads[i]
while (true){
if (count.get() >0){
//加锁前后双重判断,避免浪费锁资源