zthread学习 实例三 使用Executor器来执行线程
2011-05-21 22:16
316 查看
#include "stdafx.h" #include <iostream> #include "zthread/PoolExecutor.h" #include "zthread/ThreadedExecutor.h" #include "zthread/ConcurrentExecutor.h" #include "zthread/SynchronousExecutor.h" #include "zthread/Runnable.h" #include "zthread/PoolExecutor.h" using namespace ZThread; using namespace std; class LiftOff : public Runnable { public: LiftOff(int count, int idn = 0): countDown(count), id(idn) {} ~LiftOff() { cout<< id << " competed" <<endl; } void run() { while (countDown--) { cout << id << " : " <<countDown <<endl; } cout<<"LiftOff!" <<endl; } private: int countDown; int id; }; int _tmain(int argc, _TCHAR* argv[]) { try { //ThreadedExecutor executor; //PoolExecutor executor(5); //ConcurrentExecutor executor; SynchronousExecutor executor; for (int i = 0; i < 5; i++) { executor.execute(new LiftOff(10, i)); } cout <<"Waiting for LiftOff" <<endl; } catch (Synchronization_Exception& e) { cerr << e.what() <<endl; } cin.get(); return 0;
Executor的种类,一个Executor对象,知道如何创建合适的语境来执行Runnable对象,不同的Executor对象有不同的任务执行方式,Executor是一个虚基类,其下派生了四种执行器:
1、ThreadedExecutor:该执行器为每一个任务创建一个线程,当任务过多时,会导致过多的开销。
2、PoolExecutor:线程池,以一个有限的线程集来执行提交的任务。预先将开销很大的线程分配工作一次性做完,在可能的时候重用这些线程,这样做可以节省很多时间,因为不会为每一个线程都创建线程。不会因为任务过多而导致过多的开销。适用于有大量的任务请求时使用。
3、ConcurrentExecutor:类似于PoolExecutor,只是它只会存在一个大小固定的线程。如果多个任务被提交至ConcurrentExecutor,每一个任务都会在上一个任务执行完成之后开始执行完成,所有的任务使用同一个线程。
4、SynchronousExecutor:类似于ConcurrentExecutor,同一时刻只运行一个任务,串行代替了并发。但SynchronousExecutor不会创建和管理线程,它使用提交任务的线程,本例中使用main()函数的主线程。
异常:我们必须把线程处理代码放在一个try块中,因为如果出现错误码的话,Executor的executor函数可能会抛出Synchronization_Exception异常。
如果Executor中的任务全部完成,程序才会退出。
相关文章推荐
- zthread学习 三 使用Executor器来执行线程
- zthread学习 实例七 线程本地存储
- zthread学习 实例十 线程间的协助(四)——读者、写者
- MFC 线程创建在使用构造函数进行初始化线程的时候,创建线程实例了,但是线程并没有执行的问题
- zthread学习 实例十 线程间的协助(一)
- zthread学习 实例十 线程间的协助(一)
- zthread学习 实例十二 线程间的协助(三)——死锁
- zthread学习 实例十三 线程间的协助(四)——读者、写者
- zthread学习 实例十一 线程间的协助(二)
- (转载)Qt 的线程与事件循环——可打印threadid进行观察槽函数到底是在哪个线程里执行,学习moveToThread的使用)
- zthread学习 实例十 线程间的协助(二)
- zthread学习 实例七 线程本地存储
- Unix学习笔记-----编程练习实例------使用vfork&&execv()在程序中加载可执行程序
- Qt 的线程与事件循环——可打印threadid进行观察槽函数到底是在哪个线程里执行,学习moveToThread的使用)
- zthread学习 实例十 线程间的协助(三)——死锁
- Service学习——第五篇 使用IntentService在单独线程上执行异步任务
- Java实例说明 100个线程同时向一个银行账户中存入1元钱,在没有使用同步机制和使用同步机制情况下的执行情况
- 学习测试:Java堆栈变量、类变量、实例变量在程序中的执行效率
- 学习JPA——Hibernate Annotation使用实例
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作