cpthread.pas

来自「Delphi高级程序开发配书源代码,可以循序渐进的学习Delphi.」· PAS 代码 · 共 56 行

PAS
56
字号
unit cpThread; //cpThread是这个线程单元文件名


interface

uses
  Classes;

// 线程的定义
type
  MyThread = class(TThread) //线程名:MyThread
  private
     Answer:Integer;        //计算的结果
  protected
    procedure GiveAnswer;   //自定义的一个方法
    procedure Execute; override;
  end;

implementation

uses SysUtils,frm;
{ Important: Methods and properties of objects in visual components 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 }

//重载Execute方法
procedure MyThread.Execute;
var
  i:integer;     //计数器
begin
  FreeOnTerminate :=true;  //设置线程终止许可
  for i:=1 to 5000000 do
    begin
      if Terminated then Break;  //如果Terminated属性为True,则终止
      inc(Answer,Round(Abs(Sin(Sqrt(i)))));
      Synchronize(GiveAnswer); //用GiveAnswer来显示线程运行结果
    end;
end;

procedure MyThread.GiveAnswer;
  begin
      frm.Form1.Edit1.Text :=IntToStr(Answer);
  end;

end.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?