1.观察者设计模式
- 简单来说,观察者模式=发布者+订阅者。
- 典型的例子:猎头和寻找工作的人。找工作的人向猎头订阅,告知自己希望得到一份工作,当有新的工作机会的时候,猎头就会把这个信息通知给曾经向他订阅过的人。
2.多线程使用观察者设计模式
这里有一个场景,有个批查询请求,为了应对这种情况,需要开启一定的子线程,将批查询分拆几个小的查询,然后同步处理。主线程能够实时监控到子线程运行状态,同时保证子线程运行完能够通知的主线程。
1.主题类
public class ObservableRunnable implements Runnable {
private final LifeCycleListener lifeCycleListener;
private int id = 0;
public ObservableRunnable(final LifeCycleListener lifeCycleListener, int id) {
this.lifeCycleListener = lifeCycleListener;
this.id = id;
}
@Override
public void run() {
System.out.println("I'am query DB by[" + id +"]");
notifyEvent(new RunnableEvent(RunnableSTATE.RUNNING, Thread.currentThread(), null ));
try {
Thread.sleep(5_000);
notifyEvent(new RunnableEvent(RunnableSTATE.SUCCESS, Thread.currentThread(), null ));
} catch (InterruptedException e) {
e.printStackTrace();
notifyEvent(new RunnableEvent(RunnableSTATE.FAILED, Thread.currentThread(), e));
}
}
enum RunnableSTATE{
RUNNING, SUCCESS, FAILED
}
public static class RunnableEvent{
private RunnableSTATE state;
private Thread thread;
private Throwable throwable;
public RunnableEvent(RunnableSTATE state, Thread thread, Throwable throwable) {
this.state = state;
this.thread = thread;
this.throwable = throwable;
}
public RunnableSTATE getState() {
return state;
}
public void setState(RunnableSTATE state) {
this.state = state;
}
public Thread getThread() {
return thread;
}
public void setThread(Thread thread) {
this.thread = thread;
}
public Throwable getThrowable() {
return throwable;
}
public void setThrowable(Throwable throwable) {
this.throwable = throwable;
}
}
private void notifyEvent(RunnableEvent event){
lifeCycleListener.onEvent(event);
}
}
2.观察者类
public interface LifeCycleListener {
void onEvent(ObservableRunnable.RunnableEvent event);
}
public class ThreadLifeCycleListener implements LifeCycleListener {
public void concurQuery(List<Integer> ids){
ids.stream().forEach(i->{
new Thread(new ObservableRunnable(this, i)).start();
});
}
@Override
public void onEvent(ObservableRunnable.RunnableEvent event) {
synchronized (this){
System.out.println("thread[" + event.getThread().getName() +"]--->state[" + event.getState()+"]");
}
}
}
3.客户端
public class ThreadLifeCycleClient {
public static void main(String[] args) {
ThreadLifeCycleListener lister = new ThreadLifeCycleListener();
lister.concurQuery(Arrays.asList(1,2,3));
}
}
4.输出
I'am query DB by[1]
I'am query DB by[2]
I'am query DB by[3]
thread[Thread-0]--->state[RUNNING]
thread[Thread-2]--->state[RUNNING]
thread[Thread-1]--->state[RUNNING]
thread[Thread-0]--->state[SUCCESS]
thread[Thread-2]--->state[SUCCESS]
thread[Thread-1]--->state[SUCCESS]
5.总结
在之前,我们通过join等待多个线程,确保主线程能够知道所有的线程结束,现在运用观察者设计模式也可以实现一点,也是一个不错的选择。