您可以使用方法調用的Queue
以及一個Router
來確定哪些類的方法來調用:
public interface Camera {
public void init();
public void start();
public void stop();
public void release();
}
public class Router implements Runnable {
private final EnumMap<CameraType, Camera> cameras = new EnumMap<>(CameraType.class);
private final BlockingQueue<RouterInvocation> queue = new LinkedBlockingQueue<>();
public enum CameraType {
CAMERA1, CAMERA2, //etc
}
private enum CameraMethod {
INIT, START, STOP, RELEASE
}
private class RouterInvocation {
public final Camera camera;
public final CameraMethod cameraMethod;
public RouterInvocation(Camera c, CameraMethod cm) {
this.camera = c;
this.cameraMethod = cm;
}
}
// similar methods for start, stop, release
public void init(CameraType cameraType) {
queue.offer(new RouterInvocation(cameras.get(cameraType), INIT);
}
public void run() {
try {
while(true) {
// wait for next RouterInvocation
RouterInvocation i = queue.take();
if(i.cameraType == INIT) {
i.camera.init();
} else if // same for remaining methods
}
} catch(InterruptedException ex) {
return;
}
}
}
的好處是,你只需要提交一個Runnable
( Router
)與ExecutorService
- Router
然後負責從適當的Camera
實施調用適當的方法。
如果你決定要多線程處理隊列中,那麼你可以共享隊列多個Routers
之間,或者我的建議是移動ExecutorService
內的Router
(所以Router
不再實行Runnable
而是創建內部Runnables
來處理隊列)。
謝謝,我會檢查一下。 – Gordak
處理程序也可能類似地工作 – Sam