首页 > 其他 > 详细

关于Executor 接口

时间:2015-04-20 22:43:18      阅读:291      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!