zthread学习 三 使用Executor器来执行线程

来源:互联网 发布:tomcat端口有哪些 编辑:程序博客网 时间:2024/04/30 08:44

[cpp] view plaincopy
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. #include "zthread/PoolExecutor.h"  
  4. #include "zthread/ThreadedExecutor.h"  
  5. #include "zthread/ConcurrentExecutor.h"  
  6. #include "zthread/SynchronousExecutor.h"  
  7. #include "zthread/Runnable.h"  
  8. #include "zthread/PoolExecutor.h"    
  9.   
  10. using namespace ZThread;  
  11. using namespace std;  
  12.   
  13. class LiftOff : public Runnable  
  14. {  
  15. public:  
  16.     LiftOff(int count, int idn = 0): countDown(count), id(idn) {}  
  17.     ~LiftOff()  
  18.     {  
  19.         cout<< id << "  competed" <<endl;  
  20.     }  
  21.     void run()  
  22.     {  
  23.         while (countDown--)  
  24.         {  
  25.             cout << id << " : " <<countDown <<endl;  
  26.         }  
  27.         cout<<"LiftOff!" <<endl;  
  28.     }  
  29. private:  
  30.     int countDown;  
  31.     int id;  
  32. };  
  33.   
  34. int _tmain(int argc, _TCHAR* argv[])  
  35. {  
  36.     try  
  37.     {  
  38.         //ThreadedExecutor executor;  
  39.         //PoolExecutor executor(5);  
  40.         //ConcurrentExecutor executor;  
  41.         SynchronousExecutor executor;  
  42.         for (int i = 0; i < 5; i++)  
  43.         {  
  44.                 executor.execute(new LiftOff(10, i));  
  45.         }  
  46.         cout <<"Waiting for LiftOff" <<endl;  
  47.     }  
  48.     catch (Synchronization_Exception&  e)  
  49.     {  
  50.         cerr << e.what() <<endl;  
  51.     }  
  52.     cin.get();  
  53.     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中的任务全部完成,程序才会退出。

0 0
原创粉丝点击