参考此例子
unit ThreadsynchronizatUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
var
counter : Integer;
criticalsection : TRTLCriticalSection;
type
TCounter = class(TThread)
private
{ Private declarations }
FLabel:TLabel;
FNumber:integer;
FIdx:integer;
procedure PushTheButton;
protected
Procedure Execute;Override;
public
{ Public declarations }
Constructor Create;
end;
TForm1 = class(TForm)
Timer1: TTimer;
Timer2: TTimer;
Button2: TButton;
Edit3: TEdit;
Button1: TButton;
Memo1: TMemo;
procedure Timer1Timer(Sender: TObject);
procedure Timer2Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure ThreadaDone(Sender : TObject);
public
{ Public declarations }
a,b : TCounter;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
constructor TCounter.create;
begin
inherited Create(False);
FreeOnTerminate:=True;
end;
procedure TCounter.execute;
var
i:integer;
begin
EnterCriticalSection(criticalsection);
try
for i:=1 to 10do
begin
sleep(100);
counter := i;
Synchronize(PushTheButton);
end;
finally
LeaveCriticalSection(criticalsection);
end;
end;
procedure TCounter.PushTheButton;
begin
Form1.Memo1.Lines.Add(IntToStr(counter));
showmessage(IntToStr(counter));
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if DateTimeToStr(now)=edit3.text then
begin
a:=TCounter.create;
a.OnTerminate:=ThreadaDone;
end;
end;
procedure TForm1.Timer2Timer(Sender: TObject);
begin
if DateTimeToStr(now)=edit3.text then
begin
b:=TCounter.create;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
edit3.Text:=DateTimeToStr(now+0.00002);
end;
Procedure TForm1.ThreadaDone;
begin
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
begin
a:=TCounter.create;
a.OnTerminate:=ThreadaDone;
end;
end;
initialization
InitializeCriticalSection(criticalsection);
finalization
DeleteCriticalSection(criticalsection);
end.