您的位置:首页 > 编程语言 > Delphi

我的学习生涯(Delphi篇) - 05

2013-05-17 00:19 246 查看
多线程基本是所有程序都应该拥有的“基因”。

下例既是简单的演示。

-------------------------------------------------------------------------------------------------美丽分割线---------------------------

年代:2005

文件:my0712.7z

效果如下图:



主程序单元:

Unit2.pas

unit Unit2;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DB, ADODB, ScktComp, Sockets;

type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
Edit2: TEdit;
ADOConnection1: TADOConnection;
ServerSocket1: TServerSocket;
TcpClient1: TTcpClient;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

ThreadsRunning:integer;
implementation
uses
unit1;
{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
MyThread1,MyThread2:MyThread;
begin
ThreadsRunning:=2;
MyThread1:=MyThread.Create(Edit1,5000);
MyThread1.OnTerminate := Button2Click;
MyThread2:=MyThread.Create(Edit2,5000);
MyThread2.OnTerminate := Button2Click;
Button1.Enabled := False;

end;

procedure TForm1.Button2Click(Sender: TObject);
begin
dec(ThreadsRunning);
if ThreadsRunning=0 then
Button1.Enabled := True;

end;

end.


线程单元:

Unit1.pas

unit Unit1;

interface

uses
Classes, StdCtrls,SysUtils;

type
MyThread = class(TThread)
private
AEdit:TEdit;
MaxLoop:Integer;
CurrentLoop: Integer;

{ Private declarations }
protected
procedure DisLoop;
procedure Execute; override;

public
constructor Create(Edit:TEdit;Max:Integer);//virtual;
end;

implementation

{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,

Synchronize(UpdateCaption);

and UpdateCaption could look like,

procedure MyThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }

{ MyThread }

constructor MyThread.Create(Edit:TEdit;Max:Integer);
begin
inherited Create(False);
AEdit:=Edit;
MaxLoop:=Max;
FreeOnTerminate := True;
end;

procedure MyThread.DisLoop;
begin
AEdit.text:=InttoStr(CurrentLoop);
end;

procedure MyThread.Execute;
var
I:integer;
begin
for I:=0 to MaxLoop Do
begin
CurrentLoop:=I;
Synchronize(DisLoop);
if Terminated then Exit;
end;
end;

end.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: