求最简单的多线程例子

慢两拍 2008-07-14 03:16:10
看不懂Example 。。。谁能给个简单些的,比如 点 Button1 开始 1 加到 100000 点 Button2 终止运算
...全文
113 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
whomin 2008-07-14
  • 打赏
  • 举报
回复
Unit2为用于计数的线程

Unit2.h源代码

#ifndef Unit2H
#define Unit2H
#include <Classes.hpp>
class TAddThrd : public TThread
{
private:
TLabel *lblShowCount;
int iCount;
protected:
void __fastcall Execute();
public:
__fastcall TAddThrd(bool CreateSuspended,TLabel *in_pLabel);
};
#endif

Unit2.cpp源代码
#include <vcl.h>
#pragma hdrstop
#include "Unit2.h"
#pragma package(smart_init)
__fastcall TAddThrd::TAddThrd(bool CreateSuspended,TLabel *in_pLabel)
: TThread(CreateSuspended)
{
lblShowCount=in_pLabel;
iCount=0;
FreeOnTerminate=true;
}
void __fastcall TAddThrd::Execute()
{
while(!Terminated)
{
Sleep(10);
iCount++;
lblShowCount->Caption=IntToStr(iCount);
}
}

Unit1为程序主窗口,上面放两个Button(分别为Button1、Button2),一个Label用于显示计数值(Label1)
Unit1.h中包含上述Unit2.h,并声明个对应变量成员(TAddThrd *AddThrd);
Unit1.cpp源代码:

#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
AddThrd=new TAddThrd(true,Label1);
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
AddThrd->Resume();
}
void __fastcall TForm1::Button2Click(TObject *Sender)
{
AddThrd->Suspend();
}


编译运行即可。点Button1开始累加计数,Label1显示计数值,点Button2则暂停。

604

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder VCL组件使用和开发
社区管理员
  • VCL组件使用和开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧