java中介者模式 应用_中介者模式在JDK源码中的应用

本节主要介绍中介者模式在 JDK 源码中的应用。

打开 JDK 中的 Timer 类,查看 Timer 类的结构,会发现 Timer 类中有很多 schedule() 重载方法,如下图所示。

e4e7088bd07b311bd7382a2fb76d38fc.png

任意点开其中一个方法,会发现所有方法最终都调用了私有的 sched() 方法,源码如下。

public class Timer {

...

public void schedule(TimerTask task, long delay) {

if (delay < 0)

throw new IllegalArgumentException("Negative delay.");

sched(task, System.currentTimeMillis()+delay, 0);

}

...

private void sched(TimerTask task, long time, long period) {

if (time < 0)

throw new IllegalArgumentException("Illegal execution time.");

// Constrain value of period sufficiently to prevent numeric

// overflow while still being effectively infinitely large.

if (Math.abs(period) > (Long.MAX_VALUE >> 1))

period >>= 1;

synchronized(queue) {

if (!thread.newTasksMayBeScheduled)

throw new IllegalStateException("Timer already cancelled.");

synchronized(task.lock) {

if (task.state != TimerTask.VIRGIN)

throw new IllegalStateException(

"Task already scheduled or cancelled");

task.nextExecutionTime = time;

task.period = period;

task.state = TimerTask.SCHEDULED;

}

queue.add(task);

if (queue.getMin() == task)

queue.notify();

}

}

...

}

不论是什么样的任务加入到队列中,我们都把这个队列中的对象称为“同事”。查看 sched() 方法的源码可以看出,所有的任务(task)都放到了 Timer 类维护的 task 队列中,同事之间的通信都是通过 Timer 来协调完成的,所以,Timer 承担了中介者的角色,而 task 队列内的任务就是具体同事对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值