java抢购多线程实现
时间: 2023-10-12 14:55:26 浏览: 44
在Java中实现抢购多线程可以使用以下步骤:
1. 创建一个继承自Thread类的抢购线程类,重写run()方法。
```
public class SeckillThread extends Thread {
private Goods goods;
private int count;
public SeckillThread(Goods goods, int count) {
this.goods = goods;
this.count = count;
}
@Override
public void run() {
for (int i = 0; i < count; i++) {
synchronized (goods) {
if (goods.getStock() > 0) {
goods.decreaseStock();
System.out.println(Thread.currentThread().getName() + "抢购成功");
} else {
System.out.println(Thread.currentThread().getName() + "抢购失败");
}
}
try {
Thread.sleep(100); // 模拟网络延迟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
2. 创建一个包含库存数量的商品类。
```
public class Goods {
private int stock;
public Goods(int stock) {
this.stock = stock;
}
public int getStock() {
return stock;
}
public void decreaseStock() {
stock--;
}
}
```
3. 在启动类中创建并启动多个抢购线程。
```
public class Main {
public static void main(String[] args) {
Goods goods = new Goods(10);
Thread t1 = new SeckillThread(goods, 5);
Thread t2 = new SeckillThread(goods, 3);
Thread t3 = new SeckillThread(goods, 4);
t1.start();
t2.start();
t3.start();
}
}
```
这样,当多个线程同时对商品进行抢购时,通过使用synchronized关键字对共享资源进行同步,确保线程安全性,避免超卖或重复抢购的问题。