単純ウェブキュー


知識点:
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、異なる業務に対して複数のキューを使用する