简单的例子,先把窗体建起来:
1 主程序:
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.
2.线程部分:
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.