zthread学习 三 使用Executor器来执行线程
来源:互联网 发布:tomcat端口有哪些 编辑:程序博客网 时间:2024/04/30 08:44
- #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中的任务全部完成,程序才会退出。
0 0
- zthread学习 实例三 使用Executor器来执行线程
- zthread学习 三 使用Executor器来执行线程
- Executor(线程执行器)
- Executor--线程的执行器
- 什么是线程执行器Executor
- java使用Executor(执行器)管理线程
- 三 线程Executor框架
- java多线程 学习笔记(二)——线程执行器 Executor
- zthread学习 实例十 线程间的协助(三)——死锁
- zthread学习 实例十二 线程间的协助(三)——死锁
- java 多线程Executor----执行器的使用
- zthread学习 实例七 线程本地存储
- zthread学习 实例七 线程本地存储
- ZThread多线程库学习笔记整理三
- Java并发编程-16-线程执行器-Executor Framework
- 线程执行器的创建:Executor及其子类
- 执行器Executor
- 执行器Executor
- zThread学习 二
- Java回忆录(三)-------流程控制
- MySQL中concat函数(连接字符串)
- 建食堂
- JS 整型,浮点型转化为字符型
- zthread学习 三 使用Executor器来执行线程
- uva 202求循环小数
- C++中为什么要将析构函数设为virtual
- zthread学习 实例四 让步、休眠、优先级
- [Python]网络爬虫(一):抓取网页的含义和URL基本构成
- Matlab中一个很有用的函数:regionprops
- zthread学习 实例五 非任务对象的生存期
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- JSP页面显示倒计时