實現一個EventQueue,該Queue有如下三種狀態:
隊列滿——最多可容納多少個Event,好比一個系統最多同時能夠受理多少業務一樣;
隊列空——當所有的Event都被處理並且沒有新的Event被提交的時候,此時隊列將是空的狀態;
有Event但是沒有滿——有新的Event被提交,但是此時沒有到達隊列的上限。
示例代碼如下:
package com. wangwenjun. concurrent. chapter05;
import java. util. LinkedList;
import static java. lang. Thread. currentThread;
public class EventQueue private final int max;
static class Event private final LinkedList<Event>eventQueue
=new LinkedList<>(); private final static int DEFAULT MAX_EVENT=10;
public EventQueue()
{
this(DEFAULT_MAX_EVENT);
}
public EventQueue(int max)
{
this. max=max; public void offer(Event event)
{
synchronized(eventQueue)
if (eventQueue. size()>=max)
try
{
console("the queue is full.");
eventQueue. wait();
}
}
catch (InterruptedException e)
e. printStackTrace(); console("the new event is submitted");
eventQueue. addLast(event); eventQueue. notify();
}
}
public Event take()
{
synchronized(eventQueue)
if (eventQueue. isEmpty())
try
{
console("the queue is empty.");
eventQueue. wait();
}
catch (InterruptedE
xception e)
e. printStackTrace();
}
Event event=eventQueue. removeFirst();
this. eventQueue. notify(); console("the event"+event +"is handled.");
return event;
}
private void console(String message)
{
System. out. printf("8s:8s\n", currentThread(). getName
}
}
上述代碼,就是實現EventQueue,該Queue應有的三種狀態的示例代碼了,在EventQueue中定義了一個隊列,offer方法會提交一個Event至隊尾,如果此時隊列已經滿了,那麼提交的線程將會被阻塞,這是調用了wait方法的結果。同樣take方法會從隊頭獲取數據,如果隊列中沒有可用數據,那麼工作線程就會被阻塞,這也是調用wait方法的直接結果。