消费者抢购商品示例
举一个简单的消费者抢购商店商品(求随机数)的例子作为多线程的入门例子:
先放主函数,商店开门,然后5个消费者抢购商品:
package store;
import store.Customer;
import store.Store;
public class Applicaiton {
public static Store store = new Store();
public static void main(String[] args) {
store.open();
int i;
for (i = 1; i <= 5; i++) {
new Customer(String.valueOf(i)).buyGoods(store);
}
}
}
商店类(商店类没啥别的父类要继承直接继承Thread,否则要用接口Runnable),CheckGoodsCountThread负责每秒check一次确定商品是否卖完:
package store;
public class Store {
public int goodsCount = 100;
public void open() {
CheckGoodsCountThread storeOpenThread = new CheckGoodsCountThread();
storeOpenThread.start();
}
//check goods has been sell out
class CheckGoodsCountThread extends Thread {
@Override
public void run() {
try {
while (goodsCount >