码迷,mamicode.com
首页 > 其他好文 > 详细

关于Executor 接口

时间:2015-04-20 22:44:41      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

public interface Executor {
    /**
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);

}


对于Executor 接口不甚理解,在此mark下

/**
 * ArrayDeque不是线程安全的,所以,用作堆栈时快于 Stack,在用作队列时快于 LinkedList
 *
 */
public class MyExcutor implements Executor{
	private final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
	private final Executor executor;
	private Runnable active;
	public MyExcutor(Executor executor){
		this.executor = executor;
	}

	@Override
	public synchronized void execute(final Runnable command) {
		tasks.offer(new Runnable() {
			@Override
			public void run() {
				try {
					command.run();
				} finally {
					scheduleNext();
				}
			}
		});
		if(active == null){
			scheduleNext();
		}
	}
	protected synchronized void scheduleNext() {
		if((active = tasks.poll()) != null){
			executor.execute(active);
		}
		
	}
	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() {
			@Override
			public void run() {
				int i = 0;
				System.out.println(" i = " + (++i));
			}
		};
		Runnable r2 = new Runnable() {
			@Override
			public void run() {
				int a = 3;
				System.out.println(" a = " + (++a));
			}
		};
		Runnable r3 = new Runnable() {
			@Override
			public void run() {
				int b = 7;
				System.out.println(" b = " + (++b));
			}
		};
		MyExcutor m = new MyExcutor(new Executor() {
			@Override
			public void execute(Runnable command) {
				command.run();
			}
		});
		m.execute(r1);
		m.execute(r2);
		m.execute(r3);
		m.display();
	}
}


关于Executor 接口

标签:

原文地址:http://blog.csdn.net/kkgbn/article/details/45155589

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!