zthread学习 实例四 让步、休眠、优先级
来源:互联网 发布:tomcat端口有哪些 编辑:程序博客网 时间:2024/04/30 15:58
1、让步
Thread::yield()可以介入CPU的调度,使CPU强制放弃执行当前线程。
2、休眠
Thread:sleep()可以使线程停止执行一段时间。
Thread:sleep()可发抛出一个Interrupted_Exception,该异常必须在run()函数中捕获,因为异常是不会跨线程传播的,只能在线程内部处理。
3、优先级
Thread::setPriority()、Thread::getPriority(),可以人为的改变到线程执行的优先级,确保紧急的任务先执行。
实例如下:
- #include "stdafx.h"
- #include <iostream>
- #include <fstream>
- #include "zthread/Runnable.h"
- #include "zthread/Thread.h"
- #include "zthread/PoolExecutor.h"
- using namespace ZThread;
- using namespace std;
- const double pi = 3.141592653589793;
- const double e = 2.718281828459;
- class SimplePriorities : public Runnable
- {
- public:
- SimplePriorities(int idn = 0): id(idn), nCountDown(5){}
- ~SimplePriorities(){}
- friend ostream& operator << (ostream& os, const SimplePriorities& sp)
- {
- return os << "#" << sp.id << " priority : " <<Thread().getPriority() << "count : " << sp.nCountDown <<endl;
- }
- void run()
- {
- while (true)
- {
- for (int i = 0; i < 10000; i++)
- {
- d = d + (pi + e) /double(i);
- }
- cout << *this <<endl;
- if (--nCountDown == 0) return;
- }
- }
- private:
- int nCountDown;
- int id;
- volatile double d;
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- try
- {
- Thread high(new SimplePriorities);
- high.setPriority(Priority::High);
- for (int i = 1; i < 5; i++)
- {
- Thread low(new SimplePriorities(i));
- low.setPriority(Priority::Low);
- }
- cin.get();
- }
- catch (Synchronization_Exception& e)
- {
- cerr << e.what() <<endl;
- }
- cin.get();
- return 0;
- }
0 0
- zthread学习 实例四 让步、休眠、优先级
- zthread学习 实例四 让步、休眠、优先级
- java线程--优先级、休眠、让步、插队实例
- zthread学习 实例一
- zthread学习 实例二
- zthread学习 实例十 线程间的协助(四)——读者、写者
- zthread学习 实例十三 线程间的协助(四)——读者、写者
- zthread学习 实例六 访问控制
- zthread学习 实例七 线程本地存储
- zthread学习 实例十一 信号量机制
- zthread学习 实例六 访问控制
- zthread学习 实例七 线程本地存储
- zthread学习 实例十四 信号量机制
- zthread学习 实例十二 ZThread库基本结构的规纳
- zthread学习 实例十五ZThread库基本结构的规纳
- zthread学习 实例三 使用Executor器来执行线程
- zthread学习 实例五 非任务对象的生存期
- zthread学习 实例十 线程间的协助(一)
- 建食堂
- JS 整型,浮点型转化为字符型
- zthread学习 三 使用Executor器来执行线程
- uva 202求循环小数
- C++中为什么要将析构函数设为virtual
- zthread学习 实例四 让步、休眠、优先级
- [Python]网络爬虫(一):抓取网页的含义和URL基本构成
- Matlab中一个很有用的函数:regionprops
- zthread学习 实例五 非任务对象的生存期
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- JSP页面显示倒计时
- 简明Vim练级攻略
- LeetCode---(83) Remove Duplicates from Sorted List
- struts2的Container