2024年3月20日发(作者:)
在BCB中使用多线程实例
2013-07-26 | 分类: 编程总结 | 标签:bcb 线程 | 浏览(1000)
多线程编程是提高系统资源利用率的一种常见方式。它占用的资源更小,启动更快,还可以
实现在后台运行一些需时较长的操作。[喝小酒的网摘]/a/
一、初识TThread对象
VCL提供了用于多线程编程的TThread类,在这个类中封装了Windows关于线程机制的
Windows API,通常将它的实例成为线程对象。线程对象通过封装简化了多线程应用程序的
编写。注意,线程对象不允许控制线程堆栈的大小或安全属性。若需要控制这 些,必须使
用Windows API的CreateThread()或BeginThread()函数。不过,即使是使用Windows Thread API
函数建立和控制多线程,仍然可从一些同步线程对象或下节将要描述的方法中受益。
要在应用程序中使用线程对象,必须创建TThread的一个派生类。File|New|Thread Object,
系统会提示为新线程对象提供类名,我们将其命名为TMyThread。我们必须自行在构造函数
以及Execute()函数中添加代码。自动 生成的构造函数中有一个参数,如果为true的话线程
创建后将进入挂起状态,直到线程对象的Resume()函数被调用才开始执行。如果为false则
线 程创建后会立刻开始执行。
我们先创建一个实例来亲自感受下多线程:在窗体上放两个Button和两个Edit组件,自动
命名。然后File|New|Thread Object来创建一个线程对象,命名为TMyThread。
以下请看完整工程代码:
//Unit1.h //主窗体头文件
//---------------------------------------------------------------------------
#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <>
#include <>
#include <>
#include <>
#include "Unit2.h"
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TButton *Button1;
TButton *Button2;
TEdit *Edit1;
TEdit *Edit2;
void __fastcall Button1Click(TObject *Sender);
void __fastcall Button2Click(TObject *Sender);
void __fastcall FormCreate(TObject *Sender);
private: // User declarations
TMyThread *thread1,*thread2;
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
// //主窗体实现文件
//---------------------------------------------------------------------------
#include
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
thread1->Resume(); //单击后才启动线程
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
thread2->Resume();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
thread1=new TMyThread(true,Edit1); //创建线程对象实例
thread2=new TMyThread(true,Edit2);
}
//---------------------------------------------------------------------------


发布评论