本文整理自网络,侵删。
之前写的多线程程序都是用api直接做的,没有用过delphi自带Tthread类,刚才看了下,写了个demo,希望对新手有帮助。。。
窗体单元:
unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,myThread, StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Label2: TLabel;
Label3: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure TThreadFinsh(Sender:TObject);
public
{ Public declarations }
end;
var
Form1: TForm1;
t1,t2,t3:TThread;
implementation
{$R *.dfm}
procedure TForm1.TThreadFinsh(Sender:TObject);
begin
ShowMessage('一个线程完毕!');
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if Button1.Caption='开始1' then
begin
Button1.Caption:='关闭';
t1.Resume;
end
else
begin
Button1.Caption:='开始1';
t1.Suspend;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if Button2.Caption='开始2' then
begin
Button2.Caption:='关闭';
t2.Resume;
end
else
begin
Button2.Caption:='开始2';
t2.Suspend;
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
if Button3.Caption='开始3' then
begin
Button3.Caption:='关闭';
t3.Resume;
end
else
begin
Button3.Caption:='开始3';
t3.Suspend;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
t1:=TmyThread1.Create(Label1,10);
t1.OnTerminate:=TThreadFinsh;
t2:=TmyThread2.Create(Label2,20);
t2.OnTerminate:=TThreadFinsh;
t3:=TmyThread3.Create(Label3,30);
t3.OnTerminate:=TThreadFinsh;
end;
end.
线程单元:
unit myThread;
interface
uses
Classes,Windows,SysUtils,Forms,StdCtrls;
type
TTestThread = class(TThread)
private
FLabel:TLabel;
FSleepDec:Integer;
protected
procedure Execute; override;
public
constructor Create(lbl:TLabel;sleepSec:Integer);
end;
TmyThread1=class(TTestThread) end;
TmyThread2=class(TTestThread) end;
TmyThread3=class(TTestThread) end;
implementation
uses main;
{ TTestThread }
constructor TTestThread.Create(lbl:TLabel;sleepSec:Integer); //参数传递
begin
FLabel:=lbl;
FSleepDec:=sleepSec;
FreeOnTerminate:=True; //让线程终止是触发OnTerminate事件
inherited Create(True);//不立即执行,只有调用resume才开始
end;
procedure TTestThread.Execute;
var
i:Integer;
begin
for i:=0 to 1000 do
begin
if terminated then Break;
FLabel.Caption:=IntToStr(i);
Sleep(FSleepDec);
end;
end;
end.
相关阅读 >>
Delphi xe5开发android程序调用电话相关功能(短信息和电话)
Delphi 学习 sql 语句 - insert、update、delete
更多相关阅读请进入《Delphi》频道 >>