你们不觉得用WaitFor之类的东西会浪费资源吗?用消息多好。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Unit2,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
protected
procedure USThread(var Msg: TMessage);
message US_THREAD;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses Unit3;
{$R *.DFM}
{ TForm1 }
procedure TForm1.USThread(var Msg: TMessage);
var
Index: integer;
begin
Index:= Msg.WParam;
Memo1.Lines.Add(Format('第%d个线程结束', [Index]));
if Index < 10 then
begin
TTestThread.Create(Handle, Index+1, false);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
TTestThread.Create(Handle, 1, false);
end;
end.
/////////////////////////////////////////
unit Unit2;
interface
uses Messages;
const
US_THREAD = WM_USER + 1024;
implementation
end.
//////////////////////////////////////
unit Unit3;
interface
uses
Classes, Windows;
type
TTestThread = class(TThread)
private
{ Private declarations }
FOwnerHandle: integer;
FIndex: integer;
procedure FOnterminate(Sender: TObject);
protected
procedure Execute;
override;
public
constructor Create(OwnerHandle, Index: integer;
CreateSuspended: Boolean);
end;
implementation
uses
Unit2;
{ TTestThread }
constructor TTestThread.Create(OwnerHandle, Index: integer;
CreateSuspended: Boolean);
begin
FOwnerHandle := OwnerHandle;
FIndex:= Index;
OnTerminate := FOnterminate;
FreeOnTerminate := true;
inherited Create(CreateSuspended);
end;
procedure TTestThread.Execute;
var
i: integer;
begin
for i:=0 to 10000do
begin
end;
end;
procedure TTestThread.FOnterminate(Sender: TObject);
begin
SendMessage(FOwnerHandle, US_THREAD, FIndex, 0);
end;
end.
///////////////
D5+XP下测试通过