type
// 宣告執行序
TTestThread = class(TThread)
private
FStrings: TStrings;
procedure AddToStrings;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean; Strings: TStrings);
end;
// 列出執行序的 ThreadID
procedure TTestThread.AddToStrings;
begin
FStrings.Add('ThreadID: ' + IntToStr(ThreadID));
end;
{
CreateSuspended 建立時先不執行
Strings 要列出訊息的 Strings
}
constructor TTestThread.Create(CreateSuspended: Boolean; Strings: TStrings);
begin
inherited Create(CreateSuspended);
FStrings := Strings;
end;
procedure TTestThread.Execute;
begin
// 當未停止時列出執行序的 ThreadID
while not Terminated do
begin
Synchronize(AddToStrings);
Sleep(1000);
end;
end;
-------------------------------------------------------------------------------------------
var
TestThread: TTestThread;
procedure TForm1.FormCreate(Sender: TObject);
begin
// 印出主執行序 MainThreadID
Memo1.Lines.Add('MainThreadID: ' + IntToStr(MainThreadID));
// 建立執行序,並在建立時就執行運作
TestThread := TTestThread.Create(False, Memo1.Lines);
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// 停止執行序
TestThread.Terminate;
TestThread.Free;
end
轉貼:http://solnone.blogspot.tw/2009/05/delphi-thread.html
沒有留言:
張貼留言