高并发编程:16、观察者模式监控线程状态

一、概述

  • 观察者模式监控线程状态

二、代码

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值