观察者模式应该是使用的比较多的模式,jdk在1.0中就将它实现了,主要是一个接口一个类,分别是Observer和Observable,今天闲的无聊就用它做一个简单的定时任务功能。
先上代码:public class ObservableTest {
public static void main(String[] args) throws InterruptedException {
Interval interval = Interval.get();
CheckTime sayLol = t -> {
Thread th = Thread.currentThread();
System.out.println(th.getName() + ": LOL");
};
interval.interval(1000,t -> {
Thread th = Thread.currentThread();
System.out.println(th.getName() + ": I love you");
System.out.println("活跃线程数: " + Thread.activeCount());
});
interval.interval(1000,t -> {
Thread th = Thread.currentThread();
System.out.println(th.getName() + ": " + t);
});
interval.interval(2000,sayLol);