1 Execute只是线程的方法,当它被调用时,线程对象才开始运行;
2 上面的代码只是创建进程,是先执行Q1.Create(参数11,参数12);语句,再执行
Q2.Create(参数21,参数22);语句。但要记住,线程的运行是并行的,并不是Q1
结束后才执行Q2,而是两个可以同时运行。
3 给你个简单的例子看看:
主程式:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, unit2;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
RunThread1: TButton;
KillThread1: TButton;
RunThread2: TButton;
KillThread2: TButton;
procedure RunThread1Click(Sender: TObject);
procedure KillThread1Click(Sender: TObject);
procedure RunThread2Click(Sender: TObject);
procedure KillThread2Click(Sender: TObject);
private
{ Private declarations }
procedure Thread1Done(Sender:Tobject);
procedure Thread2Done(Sender:Tobject);
public
{ Public declarations }
Flabel1,Flabel2:Tlabel;
Thread1,Thread2:TMyThread;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.RunThread1Click(Sender: TObject);
begin
RunThread1.Enabled:=False;
KillThread1.Enabled:=True;
Thread1:=TMyThread.Create(Form1.Label1,10000);
Thread1.OnTerminate:=Thread1Done;
end;
procedure TForm1.KillThread1Click(Sender: TObject);
begin
Thread1.Terminate;
end;
procedure TForm1.RunThread2Click(Sender: TObject);
begin
RunThread2.Enabled:=False;
KillThread2.Enabled:=True;
Thread2:=TMyThread.Create(Form1.Label2,10000);
Thread2.OnTerminate:=Thread2Done;
end;
procedure TForm1.KillThread2Click(Sender: TObject);
begin
Thread2.Terminate;
end;
procedure TForm1.Thread1Done(Sender:Tobject);
begin
RunThread1.Enabled:=True;
KillThread1.Enabled:=False;
end;
procedure TForm1.Thread2Done(Sender:Tobject);
begin
RunThread2.Enabled:=True;
KillThread2.Enabled:=False;
end;
end.
线程部分:
unit Unit2;
interface
uses Classes,StdCtrls,SysUtils,Dialogs;
type
TMyThread=class(TThread)
private
Flabel:Tlabel;
Max:Integer;
Fidx:Integer;
procedure UpdateLabel;
protected
procedure Execute;override;
public
constructor create(mylabel:Tlabel;number:Integer);
end;
implementation
uses unit1;
constructor TMyThread.create(mylabel:Tlabel;number:Integer);
begin
inherited Create(False);
if number>10000 then
number:=10000;
if number<1 then
number:=1;
Max:=number;
Flabel:=mylabel;
FreeOnTerminate:=True;
end;
procedure TMyThread.Execute;
var
idx:Integer;
begin
for idx:=0 to Maxdo
begin
synchronize(UpdateLabel);
fidx:=idx;
if terminated then
exit;
end;
end;
procedure TMyThread.UpdateLabel();
begin
Flabel.caption:=IntToStr(Fidx);
end;
end.