官方对Schedulers.trampoline的解释是:
Creates and returns a Scheduler that queues work on the current thread to be executed after the current work completes.
Schedulers.trampoline调度器会将任务按添加顺序依次放入当前线程中等待执行(当前线程就是Schedulers.trampoline调度器创建Worker对象后,Worker对象调用scedule方法所在的线程)。线程一次只执行一个任务,其余任务排队等待,一个任务都执行完成后再开始下一个任务的执行。
用代码来做演示:
Scheduler.Worker worker = Schedulers.trampoline().createWorker();
Action0 act1 = () -> {
System.out.println("Action1 START:" + Thread.currentThread().getName());
System.out.println("Action1 END");
};
Action0 act2 = () -> {
System.out.println("Action2 START:" + Thread.currentThread().getName());
worker.schedule(act1);
System.out.println("Action2 END");
};
worker.schedule(act2);
调度器首先调度act2到线程线程中执行(worker.schedule调用所处的线程),act2在执行过程中,调度器又调度了一个任务act1到act2正在执行的线程上,但是act1不会立即执行而是排队等候act2执行完毕后,才开始执行。随着”Action2 END”的打印,act2执行完毕,act1获得执行。因此最终代码的运行结果为:
Action2 START:main
Action2 END
Action1 START:main
Action1 END
现在将worker.schedule(act2);方法换一个线程执行:
Scheduler.Worker worker = Schedulers.trampoline().createWorker();
Action0 act1 = () -> {
System.out.println("Action1 START:" + Thread.currentThread().getName());
System.out.println("Action1 END");
};
Action0 act2 = () -> {
System.out.println("Action2 START:" + Thread.currentThread().getName());
worker.schedule(act1);
System.out.println("Action2 END");
};
new Thread("My Thread"){
@Override
public void run() {
worker.schedule(act2);
}
}.start();
执行结果为:
Action2 START:My Thread
Action2 END
Action1 START:My Thread
Action1 END