class SerialExecutor implements Executor {
final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
final Executor executor; //添加这个进来的目的就是为了执行executor中的execute()方法。
Runnable active;
SerialExecutor(Executor executor) {
this.executor = executor;
}
public synchronized void execute(final Runnable r) {
//这里没有run()方法哦!
tasks.offer(new Runnable() { //这里只是放进去,并没有执行
public void run() {
try {
r.run(); //3
} finally {
scheduleNext();
}
}
});
if (active == null) {
scheduleNext(); //放进去,又取出来了,tasks中没有了
}
}
protected synchronized void scheduleNext() {
if ((active = tasks.poll()) != null) { //active中有run()方法。
executor.execute(active); //1 若把executor改成this,就不能得到数据了,
//因为它的execute()方法中没有run()方法。
}
}
public void display()
{
if(tasks.isEmpty())
System.out.println("this is null");
for(Runnable r :tasks)
{
System.out.println(r.toString());
}
}
public static void main(String[] args)
{
Runnable r1 = new Runnable(){
public void run() {
int i = 0;
System.out.println("i = " +(++i));
}
};
Runnable r2 = new Runnable(){
public void run() {
int a = 3;
System.out.println("a = " +(++a));
}
};
Runnable r3 = new Runnable(){
public void run() {
int b = 7;
System.out.println("b = " +(++b));
}
};
SerialExecutor executor = new SerialExecutor(new Executor(){
public void execute(Runnable command) {
command.run(); //2
}
});
executor.execute(r1);
executor.execute(r2);
executor.execute(r3);
executor.display();
}
}