需求背景
假设我们有10000张火车票在售,有10001个人同时在抢
设计
我们可以创建10001个线程模拟高并发场景,使用synchronized来进行加锁保证数据的准确性
代码实现
public class SynchronizeTest implements Runnable {
// 共享变量,假设10000张票
private int ticket = 10000;
@Override
public synchronized void run() {
ticket--;
System.out.println(Thread.currentThread().getName() + "抢到票,还剩余ticket:" + ticket);
}
public static void main(String[] args) {
SynchronizeTest thread = new SynchronizeTest();
TimeInterval timer = DateUtil.timer();
List<Thread> threads = new ArrayList<>();
// 多线程模拟10001个人同时在抢票
for (int i = 0; i < 10001; i++) {
threads.add(new Thread(thread, "用户" + i));
}
threads.forEach(thread1 -> {
thread1.start();
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("用时:"+timer.intervalRestart()+"ms");
}
}
输出:
用户0,剩余ticket:9999
用户1,剩余ticket:9998
用户3,剩余ticket:9997
用户2,剩余ticket:9996
……
用户9990,剩余ticket:0
用户9996,剩余ticket:-1
用时:2357ms
总结:
-
编号为
用户9996的用户没有抢到票。 -
可以看到
10000张票抢完用时2357ms。 -
当我们把无用
[生产环境需要去掉无用打印]的sout注释掉,用时:1495ms。