线程池的应用及Callable接口的使用
- public interface Executor {
- /**
- * Executes the given command at some time in the future. The command
- * may execute in a new thread, in a pooled thread, or in the calling
- * thread, at the discretion of the <tt>Executor</tt> implementation.
- *
- * @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);
- }
public interface Executor { /**
* Executes the given command at some time in the future. The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread, at the discretion of the <tt>Executor</tt> implementation.
*
* @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);
}
- //接口ExecutorService继承自Executor,它的目的是为我们管理Thread对象,从而简化并发编程
- public interface ExecutorService extends Executor {
- <T> Future<T> submit(Callable<T> task);
- <T> Future<T> submit(Runnable task, T result);
- Future<?> submit(Runnable task);
- ...
- }
//接口ExecutorService继承自Executor,它的目的是为我们管理Thread对象,从而简化并发编程
public interface ExecutorService extends Executor { <T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); Future<?> submit(Runnable task); ...
}
- public interface Callable<V> {
- /**
- * Computes a result, or throws an exception if unable to do so.
- *
- * @return computed result
- * @throws Exception if unable to compute a result
- */
- V call() throws Exception;
- }
- public interface Runnable {
- public abstract void run();
- }
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
} public interface Runnable { public abstract void run();
}
- public interface Future<V> {
- boolean cancel(boolean mayInterruptIfRunning);
- /**
- * Waits if necessary for the computation to complete, and then
- * retrieves its result.
- *
- * @return the computed result
- */
- V get() throws InterruptedException, ExecutionException;
- V get(long timeout, TimeUnit unit)
- throws InterruptedException, ExecutionException, TimeoutException;
- }
public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning); /**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result
*/
V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
Callable接口和Runnable接口相似,区别就是Callable需要实现call方法,而Runnable需要实现run方法;并且,call方法还可以返回任何对象,无论是什么对象,JVM都会当作Object来处理。但是如果使用了泛型,我们就不用每次都对Object进行转换了。
Runnable和Callable都是接口
不同之处:
1.Callable可以返回一个类型V,而Runnable不可以
2.Callable能够抛出checked exception,而Runnable不可以。
3.Runnable是自从java1.1就有了,而Callable是1.5之后才加上去的
4.Callable和Runnable都可以应用于executors。而Thread类只支持Runnable.
上面只是简单的不同,其实这两个接口在用起来差别还是很大的。Callable与executors联合在一起,在任务完成时可立刻获得一个更新了的Future。而Runable却要自己处理
Future接口,一般都是取回Callable执行的状态用的。其中的主要方法:
- cancel,取消Callable的执行,当Callable还没有完成时
- get,获得Callable的返回值
- isCanceled,判断是否取消了
- isDone,判断是否完成
用Executor来构建线程池,应该要做的事:
1).调用Executors类中的静态方法newCachedThreadPool(必要时创建新线程,空闲线程会被保留60秒)或newFixedThreadPool(包含固定数量的线程池)等,返回的是一个实现了ExecutorService接口的ThreadPoolExecutor类或者是一个实现了ScheduledExecutorServiece接口的类对象。
2).调用submit提交Runnable或Callable对象。
3).如果想要取消一个任务,或如果提交Callable对象,那就要保存好返回的Future对象。
4).当不再提交任何任务时,调用shutdown方法。
举2个例子如下:
- package thread.test04;
- import java.util.concurrent.*;
- public class ThreadTestA {
- public static void main(String[] args) {
- ExecutorService e=Executors.newFixedThreadPool(10);
- e.execute(new MyRunnableA());
- e.execute(new MyRunnableB());
- e.shutdown();
- }
- }
- class MyRunnableA implements Runnable{
- public void run(){
- System.out.println("Runnable:run()....");
- int i=0;
- while(i<20){
- i++;
- for(int j=0;j<1000000;j++);
- System.out.println("i="+i);
- }
- }
- }
- class MyRunnableB implements Runnable{
- public void run(){
- char c='A'-1;
- while(c<'Z'){
- c++;
- for(int j=0;j<1000000;j++);
- System.out.println("c="+c);
- }
- }
- }
- package thread.test04;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- public class ThreadTestB {
- public static void main(String[] args) {
- ExecutorService e=Executors.newFixedThreadPool(10);
- Future f1=e.submit(new MyCallableA());
- Future f2=e.submit(new MyCallableA());
- Future f3=e.submit(new MyCallableA());
- System.out.println("--Future.get()....");
- try {
- System.out.println(f1.get());
- System.out.println(f2.get());
- System.out.println(f3.get());
- } catch (InterruptedException e1) {
- e1.printStackTrace();
- } catch (ExecutionException e1) {
- e1.printStackTrace();
- }
- e.shutdown();
- }
- }
- class MyCallableA implements Callable<String>{
- public String call() throws Exception {
- System.out.println("开始执行Callable");
- String[] ss={"zhangsan","lisi"};
- long[] num=new long[2];
- for(int i=0;i<1000000;i++){
- num[(int)(Math.random()*2)]++;
- }
- if(num[0]>num[1]){
- return ss[0];
- }else if(num[0]<num[1]){
- throw new Exception("弃权!");
- }else{
- return ss[1];
- }
- }
- }
来源:http://junlas.iteye.com/blog/846457
- /**
- * Factory and utility methods for {@link Executor}, {@link
- * ExecutorService}, {@link ScheduledExecutorService}, {@link
- * ThreadFactory}, and {@link Callable} classes defined in this
- * package. This class supports the following kinds of methods:
- *
- * <ul>
- * <li> Methods that create and return an {@link ExecutorService}
- * set up with commonly useful configuration settings.
- * <li> Methods that create and return a {@link ScheduledExecutorService}
- * set up with commonly useful configuration settings.
- * <li> Methods that create and return a "wrapped" ExecutorService, that
- * disables reconfiguration by making implementation-specific methods
- * inaccessible.
- * <li> Methods that create and return a {@link ThreadFactory}
- * that sets newly created threads to a known state.
- * <li> Methods that create and return a {@link Callable}
- * out of other closure-like forms, so they can be used
- * in execution methods requiring <tt>Callable</tt>.
- * </ul>
- *
- * @since 1.5
- * @author Doug Lea
- */
- public class Executors {
- /**
- * Creates a thread pool that reuses a fixed number of threads
- * operating off a shared unbounded queue. At any point, at most
- * <tt>nThreads</tt> threads will be active processing tasks.
- * If additional tasks are submitted when all threads are active,
- * they will wait in the queue until a thread is available.
- * If any thread terminates due to a failure during execution
- * prior to shutdown, a new one will take its place if needed to
- * execute subsequent tasks. The threads in the pool will exist
- * until it is explicitly {@link ExecutorService#shutdown shutdown}.
- *
- * @param nThreads the number of threads in the pool
- * @return the newly created thread pool
- * @throws IllegalArgumentException if <tt>nThreads <= 0</tt>
- */
- public static ExecutorService newFixedThreadPool(int nThreads) {
- return new ThreadPoolExecutor(nThreads, nThreads,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<Runnable>());
- }
- /**
- * Creates a thread pool that reuses a fixed number of threads
- * operating off a shared unbounded queue, using the provided
- * ThreadFactory to create new threads when needed. At any point,
- * at most <tt>nThreads</tt> threads will be active processing
- * tasks. If additional tasks are submitted when all threads are
- * active, they will wait in the queue until a thread is
- * available. If any thread terminates due to a failure during
- * execution prior to shutdown, a new one will take its place if
- * needed to execute subsequent tasks. The threads in the pool will
- * exist until it is explicitly {@link ExecutorService#shutdown
- * shutdown}.
- *
- * @param nThreads the number of threads in the pool
- * @param threadFactory the factory to use when creating new threads
- * @return the newly created thread pool
- * @throws NullPointerException if threadFactory is null
- * @throws IllegalArgumentException if <tt>nThreads <= 0</tt>
- */
- public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
- return new ThreadPoolExecutor(nThreads, nThreads,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<Runnable>(),
- threadFactory);
- }
- /**
- * Creates an Executor that uses a single worker thread operating
- * off an unbounded queue. (Note however that if this single
- * thread terminates due to a failure during execution prior to
- * shutdown, a new one will take its place if needed to execute
- * subsequent tasks.) Tasks are guaranteed to execute
- * sequentially, and no more than one task will be active at any
- * given time. Unlike the otherwise equivalent
- * <tt>newFixedThreadPool(1)</tt> the returned executor is
- * guaranteed not to be reconfigurable to use additional threads.
- *
- * @return the newly created single-threaded Executor
- */
- public static ExecutorService newSingleThreadExecutor() {
- return new FinalizableDelegatedExecutorService
- (new ThreadPoolExecutor(1, 1,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<Runnable>()));
- }
- /**
- * Creates an Executor that uses a single worker thread operating
- * off an unbounded queue, and uses the provided ThreadFactory to
- * create a new thread when needed. Unlike the otherwise
- * equivalent <tt>newFixedThreadPool(1, threadFactory)</tt> the
- * returned executor is guaranteed not to be reconfigurable to use
- * additional threads.
- *
- * @param threadFactory the factory to use when creating new
- * threads
- *
- * @return the newly created single-threaded Executor
- * @throws NullPointerException if threadFactory is null
- */
- public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
- return new FinalizableDelegatedExecutorService
- (new ThreadPoolExecutor(1, 1,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<Runnable>(),
- threadFactory));
- }
- /**
- * Creates a thread pool that creates new threads as needed, but
- * will reuse previously constructed threads when they are
- * available. These pools will typically improve the performance
- * of programs that execute many short-lived asynchronous tasks.
- * Calls to <tt>execute</tt> will reuse previously constructed
- * threads if available. If no existing thread is available, a new
- * thread will be created and added to the pool. Threads that have
- * not been used for sixty seconds are terminated and removed from
- * the cache. Thus, a pool that remains idle for long enough will
- * not consume any resources. Note that pools with similar
- * properties but different details (for example, timeout parameters)
- * may be created using {@link ThreadPoolExecutor} constructors.
- *
- * @return the newly created thread pool
- */
- public static ExecutorService newCachedThreadPool() {
- return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
- 60L, TimeUnit.SECONDS,
- new SynchronousQueue<Runnable>());
- }
- /**
- * Creates a thread pool that creates new threads as needed, but
- * will reuse previously constructed threads when they are
- * available, and uses the provided
- * ThreadFactory to create new threads when needed.
- * @param threadFactory the factory to use when creating new threads
- * @return the newly created thread pool
- * @throws NullPointerException if threadFactory is null
- */
- public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
- return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
- 60L, TimeUnit.SECONDS,
- new SynchronousQueue<Runnable>(),
- threadFactory);
- }
- /**
- * Creates a single-threaded executor that can schedule commands
- * to run after a given delay, or to execute periodically.
- * (Note however that if this single
- * thread terminates due to a failure during execution prior to
- * shutdown, a new one will take its place if needed to execute
- * subsequent tasks.) Tasks are guaranteed to execute
- * sequentially, and no more than one task will be active at any
- * given time. Unlike the otherwise equivalent
- * <tt>newScheduledThreadPool(1)</tt> the returned executor is
- * guaranteed not to be reconfigurable to use additional threads.
- * @return the newly created scheduled executor
- */
- public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
- return new DelegatedScheduledExecutorService
- (new ScheduledThreadPoolExecutor(1));
- }
- /**
- * Creates a single-threaded executor that can schedule commands
- * to run after a given delay, or to execute periodically. (Note
- * however that if this single thread terminates due to a failure
- * during execution prior to shutdown, a new one will take its
- * place if needed to execute subsequent tasks.) Tasks are
- * guaranteed to execute sequentially, and no more than one task
- * will be active at any given time. Unlike the otherwise
- * equivalent <tt>newScheduledThreadPool(1, threadFactory)</tt>
- * the returned executor is guaranteed not to be reconfigurable to
- * use additional threads.
- * @param threadFactory the factory to use when creating new
- * threads
- * @return a newly created scheduled executor
- * @throws NullPointerException if threadFactory is null
- */
- public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
- return new DelegatedScheduledExecutorService
- (new ScheduledThreadPoolExecutor(1, threadFactory));
- }
- /**
- * Creates a thread pool that can schedule commands to run after a
- * given delay, or to execute periodically.
- * @param corePoolSize the number of threads to keep in the pool,
- * even if they are idle.
- * @return a newly created scheduled thread pool
- * @throws IllegalArgumentException if <tt>corePoolSize < 0</tt>
- */
- public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
- return new ScheduledThreadPoolExecutor(corePoolSize);
- }
- /**
- * Creates a thread pool that can schedule commands to run after a
- * given delay, or to execute periodically.
- * @param corePoolSize the number of threads to keep in the pool,
- * even if they are idle.
- * @param threadFactory the factory to use when the executor
- * creates a new thread.
- * @return a newly created scheduled thread pool
- * @throws IllegalArgumentException if <tt>corePoolSize < 0</tt>
- * @throws NullPointerException if threadFactory is null
- */
- public static ScheduledExecutorService newScheduledThreadPool(
- int corePoolSize, ThreadFactory threadFactory) {
- return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
- }
- ........
- /** Cannot instantiate. */
- private Executors() {}
- }
线程池的应用及Callable接口的使用的更多相关文章
- java多线程系类:JUC线程池:06之Callable和Future(转)
概要 本章介绍线程池中的Callable和Future.Callable 和 Future 简介示例和源码分析(基于JDK1.7.0_40) 转载请注明出处:http://www.cnblogs.co ...
- java异步线程池同时请求多个接口数据
一.主要使用类 . ExecutorService java线程池类 申明方式:ExecutorService exc = Executors.newFixedThreadPool(requestPa ...
- java多线程 -- 创建线程的第三者方式 实现Callable接口
Java 5.0 在 java.util.concurrent 提供了一个新的创建执行线程的方式:Callable 接口Callable 接口类似于 Runnable,两者都是为那些其实例可能被另一个 ...
- Java第三阶段学习(七、线程池、多线程)
一.线程池 1.概念: 线程池,其实就是一个容纳多个线程的容器,其中的线程可以重复使用,省去了频繁创建线程对象的过程,无需反复创建线程而消耗过多资源,是JDK1.5以后出现的. 2.使用线程池的方式- ...
- 多线程(Thread、线程创建、线程池)
第1章 多线程 1.1 多线程介绍 学习多线程之前,我们先要了解几个关于多线程有关的概念. 进程:进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于运行过程中的程 ...
- Java基础学习笔记: 多线程,线程池,同步锁(Lock,synchronized )(Thread类,ExecutorService ,Future类)(卖火车票案例)
多线程介绍 学习多线程之前,我们先要了解几个关于多线程有关的概念.进程:进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于运行过程中的程序,并且具有一定独立功能. 线 ...
- java基础(26):Thread、线程创建、线程池
1. 多线程 1.1 多线程介绍 学习多线程之前,我们先要了解几个关于多线程有关的概念. 进程:进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于运行过程中的程序,并 ...
- 多线程、线程池、线程创建、Thread
转载自https://www.cnblogs.com/jmsjh/p/7762034.html 多线程 1.1 多线程介绍 学习多线程之前,我们先要了解几个关于多线程有关的概念. 进程:进程指正在运行 ...
- java ->多线程_线程池
线程池概念 线程池,其实就是一个容纳多个线程的容器,其中的线程可以反复使用,省去了频繁创建线程对象的操作,无需反复创建线程而消耗过多资源. 我们详细的解释一下为什么要使用线程池?(程序优化) 在jav ...
随机推荐
- Sublime Text shift+ctrl妙用、Sublime Text快捷组合键大全
Package Control 安装方法 首先通过快捷键 ctrl+` 或者 View > Show Console 打开控制台,然后粘贴相应的 Python 安装代码. 1 :按住shift+ ...
- 2017年1月6日 星期五 --出埃及记 Exodus 21:32
2017年1月6日 星期五 --出埃及记 Exodus 21:32 If the bull gores a male or female slave, the owner must pay thirt ...
- 2016年10月14日 星期五 --出埃及记 Exodus 18:25
2016年10月14日 星期五 --出埃及记 Exodus 18:25 He chose capable men from all Israel and made them leaders of th ...
- Data
[pdf你真可爱] [题目分析] 上午考试想到用二分答案做,写残了... 设两个数列,a和b,a表示磁头,看作指针,b就是要扫描的那个序列. 假设一个答案mid,就是a中的数字走mid步能否到达b中的 ...
- PostGIS_导入shp格式的数据
1.导入shp到PostGIS 开启PostGIS shp Loader,如下图: 打开View connection details....输入连接数据库的参数,如下: 连接成功后,点击Add Fi ...
- unicode下char*和CString和一些数据之间的转换
首先mfc下字符串只有两种数据:char(一个字节)和wchar_t(两个字节),很多其他数据类型如TCHAR,WCHAR等都是这个两个基本类型的宏定义,BYTE是uchar 1.对话框打印char* ...
- VC++获取计算机Hardware Information (CPU ID, MainBoard Info, Hard Disk Serial, System Information)
转载:http://blog.csdn.net/yapingxin/article/details/50107799 转载:http://zhidao.baidu.com/link?url=A5K6N ...
- 自学QT笔记
前言: Qt 是一个跨平台的 C++图形用户界面库,由挪威 TrollTech 公司于1995年底出品. Trolltech 公司在 1994 年成立,但是在 1992 年,成立 Trolltech ...
- ZOJ 2182 Cable TV Network(无向图点割-最大流)
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2182 题意:给出一个无向图,问最少删掉多少个顶点之后图变得不连通 ...
- Linux常用命令大杂烩(持续更新)
1.vimn,$s/findstr/targetstr/g #替换n到文档末尾的所有字符串:% s/^.\{4\}//g #将当前缓冲区的所有行的前4个字符删除 2.每周日早上3:30删除日志30 3 ...