Java 线程卖票问题

描述

运用 Java 线程模拟卖票的案例。

题目

运用 Java 线程模拟卖票的案例,分别使用单线程、多线程进行卖票。

题目解决思路

  1. 创建单线程进行卖票。
  2. 创建两个线程,模拟两个窗口进行卖票。

代码具体实现

单线程卖票代码:

public class MyRunnable implements Runnable { public static int count = 1; @Override public void run() { while(true){ if(count <= 100){ System.out.println(Thread.currentThread().getName() + "卖出第" + count + "张票"); count++; }else{ System.out.println("卖光了"); break; } } } }

单线程卖票测试代码:

public class Test { public static void main(String[] args) { System.out.println("嗨客网(www.haicoder.net)\n"); // 创建单线程 MyRunnable r = new MyRunnable(); Thread t = new Thread(r,"窗口A"); t.start(); } }

运行结果如下图:

10 Java 卖票问题.png

多线程卖票代码:

public class MyRunnable implements Runnable { public static int count = 1; @Override public void run() { while(true){ if(count <= 5){ try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "卖出第" + count + "张票"); count++; }else{ System.out.println("卖光了"); break; } } } }

多线程卖票测试代码:

public class Test { public static void main(String[] args) { System.out.println("嗨客网(www.haicoder.net)\n"); MyRunnable r = new MyRunnable(); Thread t1 = new Thread(r,"窗口A"); Thread t2 = new Thread(r,"窗口B"); // 多线程会出现数据污染 t1.start(); t2.start(); } }

运行结果如下图:

11 Java 数据污染问题.png

以上案例分别使用单线程、多线程实现卖票案例,发现多线程卖票时会发生数据污染的问题,可以使用同步代码块、同步方法、Lock 锁解决该问题。