unit TChildThread;
interface
uses
Classes,Messages,Windows,SysUtils;
const MAX_LEN = 260;
type
TChildThreads = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
//同步函数的声明
procedure UpdateData;
public
szName : array[0..MAX_LEN] of Char;
nIndex : Integer;
end;
implementation
uses
Unit1;
{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TChildThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ TChildThread }
//同步函数的实现
procedure TChildThreads.UpdateData;
begin
Form1.ShowData.Items.Add(PChar(@szName));
end;
procedure TChildThreads.Execute;
begin
{ Place thread code here }
//调用同步过程
Synchronize(UpdateData);
end;
end.
主程的设计与《Delphi中多线程用消息实现VCL数据同步显示》基本一致,但为了与其显示相同结果,在生成子线程中语句顺序作了一下调整。以下代码仅显示与上一篇不同的一个过程,其它代码不再赘述。
procedure TForm1.StartThreadsClick(Sender: TObject);
var
oChildThread : array[0..1000] of TChildThreads;
i : Integer;
begin
For i := 0 to 1000 do
begin
oChildThread[i] := TChildThreads.Create(true);
//注意这里的代码与消息同步中的顺序。
oChildThread[i].nIndex := i;
strcopy(@oChildThread[i].szName,PChar('Child' + IntToStr(i)));
oChildThread[i].Resume;
end;
end;