多线程【Delphi版】

一.基本注意点

          1.访问公共变量时需要设置临界区

          2.不可直接操作界面,需通过向窗口发送消息来处理

           PS:下面的测试程序中,为简单起见,在线程中直接对主界面进行了操作,实际开发

         项目时是不应该如此操作的。

 

二.主要代码

     公共变量与临界区变量

unit GlobalVar;

interface
uses
  Windows;

var
  userCount:Integer;
  UserInfoRTL:TRTLCriticalSection;

implementation

end.

     线程定义

unit UserInfoManage_Thread;

interface

uses
  Classes, SysUtils, GlobalVar,Windows;

type
    TUserInfoManage_Thread= class(TThread)
    private

    public
      constructor Create(CreateSuspended: Boolean);
      procedure  Execute;override;
      destructor Destroy;override;
  end;

implementation
uses
  Main;
{ TUserInfoManage_Thread }

constructor TUserInfoManage_Thread.Create(CreateSuspended: Boolean);
begin
   inherited Create(CreateSuspended);
end;

destructor TUserInfoManage_Thread.Destroy;
begin

  inherited;
end;

procedure TUserInfoManage_Thread.Execute;
var
  printStr:string;
begin
  inherited;

  EnterCriticalSection(UserInfoRTL);//进入临界区
  try
    userCount:=userCount+1;

    printStr:=''+inttostr(userCount)+'个线程已启动,并进入临界区';
    FrmMain.Memo1.Lines.Add(printStr);

    printStr:='休眠2000毫秒。。。';
    FrmMain.Memo1.Lines.Add(printStr);
    Sleep(2000);

    printStr:=''+inttostr(userCount)+'个线程执行完毕,离开临界区';
    FrmMain.Memo1.Lines.Add(printStr+#13#10);
  finally
    LeaveCriticalSection(UserInfoRTL);//离开临界区
  end;

  Self.FreeOnTerminate:=True;
end;

end.

      主程序初始化“临界区变量”

   userCount:=0;
   InitializeCriticalSection(UserInfoRTL);

      连续启动多个线程

begin
  TUserInfoManage_Thread.Create(False);

  TUserInfoManage_Thread.Create(False);

  TUserInfoManage_Thread.Create(False);
end;

 

 

三.运行结果

   

posted @ 2012-05-23 16:58  edisonfeng  阅读(1002)  评论(2编辑  收藏  举报