package com.ticketcase;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Author: Harry Chen
* Date: 2023/02/13 16:25
* Description: 测试 synchronized 的买票案例
*/
public class Test {
private int count;
public Test(int count) {
this.count = count;
}
public synchronized void buyNum(int num) {
while (count >= 1){
this.count -= num;
System.out.println("卖掉" + (this.count + num) + "号票。还剩:" + this.count);
}
}
public static void main(String[] args) {
Test test = new Test(100);
Thread thread1 = new Thread(() -> {
try {
test.buyNum(1);
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread2 = new Thread(() -> {
try {
test.buyNum(1);
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread3 = new Thread(() -> {
try {
test.buyNum(1);
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 5, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
executor.execute(thread1);
executor.execute(thread2);
executor.execute(thread3);
}
}
测试 synchronized 的买票案例
最新推荐文章于 2024-08-15 14:47:41 发布
该代码示例展示了如何使用`synchronized`关键字处理多线程同步问题,以确保在卖票场景中不会出现数据不一致。创建了三个线程模拟购票,通过`ThreadPoolExecutor`执行,使用`LinkedBlockingQueue`作为工作队列。
摘要由CSDN通过智能技术生成