java--Executor

public interface Executor(){
	void ecextor(Runnable command);
}

主要方法:

创建线程池:

// 1、
// newFixedThreadPool(); 
// 创建一个固定线程数量的线程池,每当提交一个任务时就创建一个线程,
// 直到达到线程池数量,这时线程池的规模将不会变化
Executor exec = Executors.newFixedThreadPool(100);

Runnable task = new Runnable(){
	public void run(){
		//do something
	}
};
exec.execute(task);
// 2、
// newCacheThreadPool(); 
// 创建一个可缓存的线程池,如果线程池规模超过了处理需求时,那么将回收空闲的线程,
// 当需求增加时,则添加新的线程,线程池规模没有限制。

// 3、
// newSingleThreadPool();
// 这是一个单线程的Executor,他创建单个工作线程来执行任务,如果这个线程异常结束
// 则会创建另一个来代替,他能确保任务在队列中串行执行(FIFO,LIFO,优先级)。内部提供了大量同步机制,
// 确保任务执行的操作对后续线程都是可见的。

// 4、
// newScheduledThreadPool()
// 创建一个固定线程的线程池,可以延迟或者定时执行

用法:

// 多线程执行
public class ThreadTask implements Executor{
	public void execute(Runnable r){
		new Thread(r).start();
	};
}

// 串行
public class Task implements Executor{
	public void execute(Runnable r){
		r.run();
	};
}

和Future Callable一起使用

// ExecutorService 继承了 Executor
ExecutorService exec =  ...;

Callable task = new Callable(){
	public Result call(){
		// do something
		return new Result();
	}
};

Future future = exec.submit(task);

future.get();

invokeAll() (ExecutorService)

/**
     * Executes the given tasks, returning a list of Futures holding
     * their status and results when all complete.
     * {@link Future#isDone} is {@code true} for each
     * element of the returned list.
     * Note that a <em>completed</em> task could have
     * terminated either normally or by throwing an exception.
     * The results of this method are undefined if the given
     * collection is modified while this operation is in progress.
     *
     * @param tasks the collection of tasks
     * @param <T> the type of the values returned from the tasks
     * @return a list of Futures representing the tasks, in the same
     *         sequential order as produced by the iterator for the
     *         given task list, each of which has completed
     * @throws InterruptedException if interrupted while waiting, in
     *         which case unfinished tasks are cancelled
     * @throws NullPointerException if tasks or any of its elements are {@code null}
     * @throws RejectedExecutionException if any task cannot be
     *         scheduled for execution
     */
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;

CompletionService

image.png

image.png

image.png

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值