// E003
//http://www.orsci.cn
//功能:演示多线程的基本操作
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#include "orsciJWVCL.h"
using namespace orsci; //orsci包的命名空间。
class TA : public TThread
{
public:
TA(const bool ACreateSuspended = true) : TThread(ACreateSuspended) {}
public:
virtual unsigned long Execute() //线程执行函数
{ //子类需要重载该方法实现子线程的功能
cout << "[TA]TThread::Execute()!ThreadID= " << idThread << " handleThread = " << handleThread << endl;
for (int k = 0; k < 100; k ++)
{
if (FTerminated) return 0; //如果外界要求线程结束,则停止。
Sleep(300);
cout << "TA = " << k << endl;
}
return 0;
}
};
class TB : public TThread
{
public:
TB(const bool ACreateSuspended = true) : TThread(ACreateSuspended) {}
public:
virtual unsigned long Execute() //线程执行函数。
{
cout << "[TB]TThread::Execute()!ThreadID= " << idThread << " handleThread = " << handleThread << endl;
for (int k = 0; k < 100; k ++)
{
if (FTerminated) return 0; //如果外界要求线程结束,则停止。
Sleep(500);
cout << " ...TB = " << k << endl;
}
return 0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
cout << "E003:多线程的演示操作!http://www.orsci.cn" << endl;
cout << "后面发现TA和TB交替输出!" << endl;
{
TA a;
TB b;
a.Resume();
b.Resume();
for (int k = 0; k <= 60; k ++)
{
cout << "Time run ... " << k << " ..." << endl;
Sleep(1000);
}
//方式一:等待线程执行完毕
//a.Waitfor();
//b.Waitfor();
//方式二:结束线程的执行
a.Terminate(false);
b.Terminate(false);
}
cout << "Press any key to continue...";
char pp;
cin >> pp;
return 0;
}
|