一、概述
- 观察者模式监控线程状态
二、代码
Client
public class Client {
public static void main(String[] args) {
ThreadLifeCycleObserver observer = new ThreadLifeCycleObserver();
observer.query(Arrays.asList("线程1","线程2","线程3"));
}
}
LifeCycleListener
public interface LifeCycleListener {
public void onEvent(RunnableStatus status, Thread thread);
}
ThreadLifeCycleObserver
public class ThreadLifeCycleObserver implements LifeCycleListener {
private final Object LOCK = new Object();
public void query(List<String> ids) {
for(int i = 0; i < ids.size(); i++) {
new Thread(new ObserverRunnable(this) {
public void run() {
try {
onEvent(RunnableStatus.RUNNING, Thread.currentThread()); // 运行中
// 构建1~10秒的等待时间 -> 为偶数时特意制造异常
int i = (new Random().nextInt(10)+1)*1000;
System.out.println(Thread.currentThread().getName() + " time: " + i);
Thread.sleep(i);
if(i % 2000 == 0) {
int j = 1/0;
System.out.println(j);
}
onEvent(RunnableStatus.DONE, Thread.currentThread()); // 运行结束
} catch (Exception e) {
onEvent(RunnableStatus.ERROR, Thread.currentThread()); // 异常
}
}
},ids.get(i)).start();
}
}
public void onEvent(RunnableStatus status, Thread thread) {
synchronized(LOCK) {
System.out.println(thread.getName() + " status: " + status);
}
}
}
ObserverRunnable
public abstract class ObserverRunnable implements Runnable {
private LifeCycleListener listener;
public ObserverRunnable(LifeCycleListener listener) {
super();
this.listener = listener;
}
public enum RunnableStatus {
RUNNING, // 运行中
DONE, // 运行结束
ERROR // 异常
}
public void notifyChange(RunnableStatus status, Thread thread) {
listener.onEvent(status,thread);
}
}
线程1 status: RUNNING
线程3 status: RUNNING
线程2 status: RUNNING
线程1 time: 7000
线程2 time: 2000
线程3 time: 10000
线程2 status: ERROR
线程1 status: DONE
线程3 status: ERROR