试试?(下面这个程序你可以试一下,如果不采用线程序来执行SumRec过程的话,在按下
Button1执行SumRec过程时Button2是无效的,而用线程执行的情况下Button2却是有效的)
虽然我设了FreeOnTerminate,但我现在还不能证实线程在执行完SumRec过程后会自动释放,
哪位大侠能给点意见?
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TMyThread = class(TThread)
protected
procedure Execute;
override;
public
constructor Create(CreateSuspended: Boolean);
end;
TForm1 = class(TForm)
Button1: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
procedure SumRec;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
Thrd1: TMyThread;
implementation
{$R *.DFM}
constructor TMyThread.Create(CreateSuspended: Boolean);
begin
inherited;
Priority := tpLower;
//设线程的优先级为较低
FreeOnTerminate := True;
//在线程中止时释放线程
end;
procedure TMyThread.Execute;
begin
Form1.SumRec;
end;
procedure TForm1.SumRec;
var I: Integer;
begin
I:=0;
while I<1000000000do
Inc(I,1);
MessageBox(Handle,PChar(IntToStr(I)+''),'',MB_OK);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Thrd1 := TMyThread.Create(False);
//False表示一创建就开始执行线程
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
ShowMessage('Hello, World!');
end;
end.