多线程模拟公平抢票
为了解决如何模拟 100 个人抢 10 张票的问题,需要确保公平性。以下是一些可供参考的解决方案:
import java.util.concurrent.locks.ReentrantLock; public class FairTicket搶票 { private static final int TOTAL_TICKETS = 10; private static final int TOTAL_USERS = 100; // 使用公平锁 private static ReentrantLock fairLock = new ReentrantLock(true); public static void main(String[] args) { for (int i = 0; i < TOTAL_USERS; i++) { new Thread(() -> { fairLock.lock(); try { if (TOTAL_TICKETS > 0) { System.out.println("用户" + Thread.currentThread().getName() + "抢到了第" + TOTAL_TICKETS + "张票"); TOTAL_TICKETS--; } else { System.out.println("用户" + Thread.currentThread().getName() + "没有抢到票"); } } finally { fairLock.unlock(); } }).start(); } } }
以上就是如何使用多线程模拟公平抢票?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号