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
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于