卖票
public class TicketDemo {
/**
* 模拟多人买票
* @param args
*/
public static void main(String[] args) {
// 创建一个售票窗口
TicketWindow ticketWindow = new TicketWindow(1000);
// 集合存入所有的线程对象
List<Thread> threadList = new ArrayList();
// Vector是线程安全的类,记录每个线程卖出的票数
List<Integer> sellCount = new Vector();
for (int i = 0; i < 2000; i++) {
Thread t = new Thread(() -> {
int count = ticketWindow.sell(randomAmount());
sellCount.add(count);
});
threadList.add(t);
t.start();
}
//等待所有的线程都执行完毕
threadList.forEach( thread -> {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// 统计所有卖出的票数
int totalSellCount = sellCount.stream().mapToInt(c -> c).sum();
System.out.println("卖出总票数:"+ totalSellCount);
System.out.println("剩余票数:" +ticketWindow.getCount());
}
static Random random = new Random();
public static int randomAmount() {
return random.nextInt(5) + 1;
}
}
/**
* 售票窗口
*/
class TicketWindow {
// 票的数量
private int count;
public TicketWindow(int count) {
this.count = count;
}
/**
* 获取余票数量
* @return
*/
public int getCount() {
return count;
}
/**
* 卖票
* @param amount
* @return
*/
public int sell(int amount) {
if(this.count > amount) {
this.count -= amount;
return amount;
} else {
return 0;
}
}
}
问题分析
多个线程运行的地方,有ticketWindow和threadList两个变量,ticketWindow中有共享变量count的修改。threadList也是被多个线程共享并执行添加操作,但是Vector本身就是线程安全的,所以不用考虑。但是ticketWindow中的sell方法对共享变量count进行了修改操作,需要加锁来保证线程安全问题。