简单web 排队器
程序员文章站
2022-04-20 23:51:06
...
知识点:
1、1.5以上的线程池
2、阻塞队列
实现:
1、排号器(队伍)
import java.util.concurrent.ArrayBlockingQueue; /** * 排队器 * * @author luoqinglong * @date 2014-3-23 */ public class BuyQueue extends ArrayBlockingQueue<String> { /** * @param capacity */ public BuyQueue(int capacity) { super(capacity); // TODO Auto-generated constructor stub } }
2、控制类
import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.Future; /** * 会员控制器 * * @author luoqinglong * @date 2014-3-23 */ public class MemberAction { /** * 提交订单 */ public void saveOrder(final String memberId) { // TODO INSERT DB try { // 排队 Test.getBuyQueue().put(memberId); } catch (InterruptedException e) { e.printStackTrace(); } // 增加排队人携带的任务 Future<Map<String, Object>> map = Test.getExecutorService().submit(new Callable<Map<String, Object>>() { @Override public Map<String, Object> call() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); OrderService orderService = new OrderService(); orderService.dealOrder(); return map; } }); } }
3、业务类
public class OrderService { /** * 按照会员下单的顺序处理订单 */ public synchronized void dealOrder() { String memberId = Test.getBuyQueue().poll(); System.out.println("开始处理订单,会员号: " + memberId); try { // 模拟业务处理时长 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("---处理完成订单,会员号: " + memberId); if (Test.getBuyQueue().size() == 0) { Test.getExecutorService().shutdown(); } } }
4、测试类
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author luoqinglong * @date 2014-3-23 */ public class Test { private static ExecutorService executor = null; private static BuyQueue buyQueue = null; /** * @param args */ public static void main(String[] args) { for (int i = 0; i < 100; i++) { MemberAction action = new MemberAction(); action.saveOrder(i + 1 + ""); } } public static synchronized ExecutorService getExecutorService() { if (Test.executor == null) { Test.executor = Executors.newFixedThreadPool(3); } return Test.executor; } public static synchronized BuyQueue getBuyQueue() { if (Test.buyQueue == null) { Test.buyQueue = new BuyQueue(10); } return Test.buyQueue; } }
需完善的地方:
1、防止重复排队
2、针对不同的业务使用多个排队器