多线程卖票小程序
时间: 2025-06-01 11:13:47 浏览: 20
### 多线程卖票小程序实现方法
多线程卖票程序的核心在于确保多个线程同时访问共享资源(如票数)时不会产生冲突或重复售票。以下是实现该功能的详细说明:
#### 1. 使用 `Runnable` 接口
通过实现 `Runnable` 接口,可以将线程逻辑封装到一个类中,并通过多个线程共享同一个对象来操作共享资源。例如,以下代码展示了如何使用 `Runnable` 实现多线程卖票[^1]。
```java
class MyThread implements Runnable {
private int ticket = 5;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
if (this.ticket > 0) {
synchronized (this) { // 确保线程安全
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName() + " 卖票, ticket = " + this.ticket--);
}
}
}
}
}
}
public class Pro {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread threadA = new Thread(myThread, "车站A");
Thread threadB = new Thread(myThread, "车站B");
Thread threadC = new Thread(myThread, "车站C");
threadA.start();
threadB.start();
threadC.start();
}
}
```
#### 2. 使用同步机制确保线程安全
在多线程环境中,必须使用同步机制(如 `synchronized` 关键字)来确保对共享资源的访问是线程安全的。以下代码展示了如何通过 `synchronized` 块避免多个线程同时修改共享变量[^2]。
```java
class SaleTicket implements Runnable {
private int count = 50;
@Override
public void run() {
while (true) {
synchronized (this) { // 使用同步块保护共享资源
if (count > 0) {
System.out.println(Thread.currentThread().getName() + " 售出了第 " + count + " 张票");
count--;
} else {
System.out.println("售罄了...");
break;
}
}
}
}
}
public class Demo2 {
public static void main(String[] args) {
SaleTicket s1 = new SaleTicket();
Thread t1 = new Thread(s1, "窗口1");
Thread t2 = new Thread(s1, "窗口2");
Thread t3 = new Thread(s1, "窗口3");
t1.start();
t2.start();
t3.start();
}
}
```
#### 3. 使用 `Lock` 接口替代 `synchronized`
除了 `synchronized`,还可以使用 `Lock` 接口(如 `ReentrantLock`)来实现更灵活的锁机制。以下是一个使用 `Lock` 的示例[^3]。
```java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class MyRunable implements Runnable {
private int ticket = 5;
private final Lock lock = new ReentrantLock(); // 定义锁
@Override
public void run() {
for (int i = 0; i < 5; i++) {
lock.lock(); // 加锁
try {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + " 卖票, ticket = " + ticket--);
}
} finally {
lock.unlock(); // 解锁
}
}
}
}
public class Demo {
public static void main(String[] args) {
MyRunable my1 = new MyRunable();
Thread th1 = new Thread(my1, "窗口1");
Thread th2 = new Thread(my1, "窗口2");
Thread th3 = new Thread(my1, "窗口3");
th1.start();
th2.start();
th3.start();
}
}
```
#### 注意事项
- 共享资源必须通过同步机制保护,以防止数据竞争。
- 使用 `synchronized` 或 `Lock` 时,需确保锁的正确释放,否则可能导致死锁。
- 线程启动顺序无法保证,因此输出结果可能因线程调度而不同。
阅读全文
相关推荐




















