我的目標是按順序發佈異步事件,這些異步事件也按順序到達並且需要任意時間進行處理。所以下面是我目前的實施只使用wait
和notify
。 MyThread
處理事件,按id將結果放入哈希表,並在發佈此事件前按順序通知Scheduler
線程(如果它已被阻止)。按順序處理異步事件併發布結果
使用java.util.concurrent
包實現此功能的方法會更好,更簡潔嗎?
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
public class AsyncHandler {
private final Map<Integer, Object> locks = new ConcurrentHashMap<Integer, Object>();
private final Map<Integer, Result> results = new ConcurrentHashMap<Integer, Result>();
private static final Random rand = new Random();
public AsyncHandler() {
new Scheduler(this, locks, results).start();
}
public void handleEvent(Event event) {
System.out.println("handleEvent(" + event.id + ")");
new MyThread(this, event, locks, results).start();
}
public Result processEvent (Event event) {
System.out.println("processEvent(" + event.id + ")");
locks.put(event.id, new Object());
try {
Thread.sleep(rand.nextInt(10000));
} catch (InterruptedException e) {
System.out.println(e);
}
return new Result(event.id);
}
public void postProcessEvent (Result result) {
System.out.println(result.id);
}
public static void main (String[] args) {
AsyncHandler async = new AsyncHandler();
for (int i = 0; i < 100; i++) {
async.handleEvent(new Event(i));
}
}
}
class Event {
int id;
public Event (int id) {
this.id = id;
}
}
class Result {
int id;
public Result (int id) {
this.id = id;
}
}
class MyThread extends Thread {
private final Event event;
private final Map<Integer, Object> locks;
private final Map<Integer, Result> results;
private final AsyncHandler async;
public MyThread (AsyncHandler async, Event event, Map<Integer, Object> locks, Map<Integer, Result> results) {
this.async = async;
this.event = event;
this.locks = locks;
this.results = results;
}
@Override
public void run() {
Result res = async.processEvent(event);
results.put(event.id, res);
Object lock = locks.get(event.id);
synchronized (lock) {
lock.notifyAll();
}
}
}
class Scheduler extends Thread {
private int curId = 0;
private final AsyncHandler async;
private final Map<Integer, Object> locks;
private final Map<Integer, Result> results;
public Scheduler (AsyncHandler async, Map<Integer, Object> locks, Map<Integer, Result> results) {
this.async = async;
this.locks = locks;
this.results = results;
}
@Override
public void run() {
while (true) {
Result res = results.get(curId);
if (res == null) {
Object lock = locks.get(curId);
//TODO: eliminate busy waiting
if (lock == null) {
continue;
}
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
System.out.println(e);
System.exit(1);
}
}
res = results.get(curId);
}
async.postProcessEvent(res);
results.remove(curId);
locks.remove(curId);
curId++;
}
}
}
您可以使用[的ConcurrentLinkedQueue(http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html)來處理傳入事件的cuncurency和秩序,啓動結果[Future](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html)並將它們放入隊列中的線程 –