1.新建窗口项目,在画面上放两个按钮:button1,button2
2.新建一个类 A
//class A的头文件
#ifndef Unit3H
#define Unit3H
//---------------------------------------------------------------------------
class A
{
public:
int id;
void Add();
void Display();
A():id(0)
{};
~A(){};
};
#endif
//class A 的cpp文件
//---------------------------------------------------------------------------
#pragma hdrstop
#include "Unit3.h"
#include "string"
#include "windows.h”
//---------------------------------------------------------------------------
#pragma package(smart_init)
void A::Add()
{
id++;
Sleep(10);
}
void A::Display()
{
char str [20];
sprintf(str,"id=%d\n",id);
OutputDebugStringA(str);
}
3.新建个线程文件
//class MyThread的头文件
//---------------------------------------------------------------------------
#ifndef Unit4H
#define Unit4H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include "Unit3.h"
//---------------------------------------------------------------------------
class MyThread : public TThread
{
private:
int i;
A * m_pA;
protected:
void __fastcall Execute();
public:
__fastcall MyThread(A * pA,bool CreateSuspended);
};
//---------------------------------------------------------------------------
#endif
//class MyThread的cpp文件
//---------------------------------------------------------------------------
#include <System.hpp>
#pragma hdrstop
#include "Unit4.h"
#pragma package(smart_init)
//---------------------------------------------------------------------------
__fastcall MyThread::MyThread(A *pA,bool CreateSuspended)
: TThread(CreateSuspended),m_pA(pA)
{
}
//---------------------------------------------------------------------------
void __fastcall MyThread::Execute()
{
while(!Terminated)
{
m_pA->Add();
}
}
4.在画面上的两个按钮程序中放入程序
//button1的
thread1=new MyThread(&aaaa,true);//新建线程,挂起
thread1->Resume();//恢复线程
//button2的
aaaa.Display();
thread1-> Terminate();
5.在画面上放Label1,Timer1,双击Timer1,放入程序
char str [20];
sprintf(str,"%d",aaaa.id);
Label1->Caption= str;