unit Unit1;
{$IFDEF FPC}{$mode Delphi}{$ENDIF}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TMathThread }
TMathThread =
class(TThread)
protected
FValue: extended;
FLabel: TLabel;
procedure UpdateGUI;
public
constructor Create(OutputLabel: TLabel);
end;
{ TAddThread }
TAddThread =
class(TMathThread)
procedure Execute;
override;
end;
{ TMulThread }
TMulThread =
class(TMathThread)
procedure Execute;
override;
end;
{ TSubThread }
TSubThread =
class(TMathThread)
procedure Execute;
override;
end;
{ TfrmMain }
TfrmMain =
class(TForm)
btnAdd: TButton;
btnMul: TButton;
btnSub: TButton;
lblAdd: TLabel;
lblMul: TLabel;
lblSub: TLabel;
procedure btnMulClick(Sender: TObject);
procedure btnSubClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ private declarations }
FAddThread, FMulThread, FSubThread: TMathThread;
public
{ public declarations }
end;
var
frmMain: TfrmMain;
implementation
{ TfrmMain }
procedure TfrmMain.btnAddClick(Sender: TObject);
begin
FAddThread.Resume;
end;
procedure TfrmMain.btnMulClick(Sender: TObject);
begin
FMulThread.Resume;
end;
procedure TfrmMain.btnSubClick(Sender: TObject);
begin
FSubThread.Resume;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
FAddThread := TAddThread.Create(lblAdd);
FMulThread := TMulThread.Create(lblMul);
FSubThread := TSubThread.Create(lblSub);
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
// TThread.Free calls TThread.Terminate internally and waits for the thread
// to end
FAddThread.Free;
FMulThread.Free;
FSubThread.Free;
end;
{$IFDEF FPC}
{$R *.lfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
{ TMathThread }
procedure TMathThread.UpdateGUI;
begin
FLabel.Caption := FloatToStr(FValue);
end;
constructor TMathThread.Create(OutputLabel: TLabel);
begin
// Create Suspended
inherited Create(True);
FLabel := OutputLabel;
FValue := 1.0;
end;
{ TSubThread }
procedure TSubThread.Execute;
begin
while not Terminated
do
begin
FValue := FValue - 1;
sleep(100);
Synchronize(UpdateGUI);
end;
end;
{ TMulThread }
procedure TMulThread.Execute;
begin
while not Terminated
do
begin
FValue := FValue * 1.01;
sleep(100);
Synchronize(UpdateGUI);
end;
end;
{ TAddThread }
procedure TAddThread.Execute;
begin
while not Terminated
do
begin
FValue := FValue + 1;
sleep(100);
Synchronize(UpdateGUI);
end;
end;
end.