您的位置:首页 > 其它

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中的任务全部完成,程序才会退出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐