程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> Thread類的創建及使用

Thread類的創建及使用

編輯:Delphi
一、Thread類的創建:

  unit Thread;
  {             線程類的創建
    編譯環境: Windows 2003 Sever  Delphi 7.0 Enterprise
  }
  interface
  uses classes,sysutils,StdCtrls;
  type
    TB = class(TThread)
    private
      i :integer;
      Fedt :TEdit;
      procedure Update ;
    public
      procedure execute;override;
      constructor create(IsSuspended :Boolean;edt :TEdit);
    end;
  implementation
  uses MainForm;

  procedure TB.Update;
  begin
    Fedt.Text :=inttostr(i);
  end;

  constructor TB.create(IsSuspended: Boolean; edt: TEdit);
  begin
    inherited create(IsSuspended);
    Fedt := edt;
  end;

  procedure TB.execute;
  begin
    i:=0;
    while(not Terminated) do
    begin
      Synchronize(Update);
      inc(i);
    end;
  end;
  end.

  二、Thread類的使用:

  unit MainForm;

  interface

  uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
    Dialogs, StdCtrls,Thread;

  type
    TfrmMain = class(TForm)
      Button1: TButton;
      Button2: TButton;
      Edit1: TEdit;
      Edit2: TEdit;
      procedure FormCreate(Sender: TObject);
      procedure FormClose(Sender: TObject; var Action: TCloseAction);
      procedure ButtonClick(Sender: TObject);
    private
      { Private declarations }
    public
      { Public declarations }
    end;

  
  var
    frmMain: TfrmMain;
    a,b:TB;
  implementation

  {$R *.dfm}

  procedure TfrmMain.FormCreate(Sender: TObject);
  begin
    a:=TB.create(true,edit1);
    b:=TB.create(True,edit2);
  end;

  procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
  begin
    freeandnil(a);freeandnil(b);
  end;

  procedure TfrmMain.ButtonClick(Sender: TObject);
  var c :TB;
  begin
    if sender = Button1 then c :=a
    else c:=b;
    if c.Suspended then begin
      c.Resume ; (sender as TButton).Caption :='暫停';
    end else begin
      c.Suspend ;(Sender as TButton).Caption :='開始';
    end;
  end;

  

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved