卖票案例线程安全问题,出现重复的票数和负票的解决方案。
线程安全问题出现的前提:多线程环境,存在共享数据,存在多个线程同时操作共享数据。
- /*
- * 买票系统解决线程安全问题案例
- */
- public class SellTicketDemo {
- public static void main(String[] args) {
-
- SellTicket st = new SellTicket();
-
- Thread th1 = new Thread(st, "窗口1:");
- Thread th2 = new Thread(st, "窗口2:");
- Thread th3 = new Thread(st, "窗口3:");
-
- th1.start();
- th2.start();
- th3.st<div class="blockcode"><blockquote>public class SellTicket implements Runnable {
- // 创建票
- private int ticket = 100;
- // 创建锁对象
- private Object obj = new Object();
- @Override
- public void run() {
- while (ticket > 0) {
- synchronized (obj) {
- if (ticket > 0) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()
- + "正在出售第" + (ticket--) + "张票");
- }
- }
- }
- }
- }
复制代码
art();
}
}
|
|