delphi一个简单的多线程例子

delphi一个简单的多线程例子

我的这个示例实为一个主线程,两个辅线程,辅线程是重新定义了两线程类,Tthread1和Tthread2,都是从Tthread继承而来。

关键是两个辅线程的Execute事件重载了祖先类Tthread的Execute.实现了相应的功能。这两个线程的事件可同时执行,无需等待。

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
Tthread1 = class(Tthread)
protected
procedure Execute;override;
end;
type
Tthread2 = class(Tthread)
protected
procedure Execute;override;
end;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
st1: TStaticText;
st2: TStaticText;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}
procedure Tthread1.Execute;
var
i: integer;
begin
FreeOnTerminate:=true;
for i:=1 to 10000 do
begin
form1.st1.Caption:= inttostr(i);
application.ProcessMessages;
end;
end;

procedure Tthread2.Execute;
var
i: integer;
begin
FreeOnTerminate:=true;
for i:=1 to 10000 do
begin
form1.st2.Caption:= inttostr(i);
application.ProcessMessages;
end;
end;


procedure TForm1.Button1Click(Sender: TObject);
var
mythread:Tthread1;
begin
mythread:=Tthread1.Create(false);
end;

procedure TForm1.Button2Click(Sender: TObject);
var
mythread:Tthread2;
begin
mythread:=Tthread2.Create(false);
end;

end.

 

THE END