Delphi多线程测试

来源:互联网 发布:sql select 统计 编辑:程序博客网 时间:2024/05/16 01:25

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  hMutex: THandle = 0;

implementation
uses unit2;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  listbox1.Items.Clear;
  ThreadT1.create(100, 'A');
  ThreadT1.create(100, 'B');
  ThreadT1.create(100, 'C');
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  hMutex := CreateMutex(nil, False, nil);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  CloseHandle(hMutex);
end;

end.

---------------------------------------------

unit Unit2;

interface

uses
  Classes, SysUtils, Windows, unit1;

type
  ThreadT1 = class(TThread)
  private
    FiMax: integer;
    Foption: string;
    Fi: integer;
    { Private declarations }
  protected
    procedure Execute; override;
    procedure AddItem();
  public
    constructor create(iMax: integer; option: string);
  end;

  ThreadT2 = class(TThread)
  private
    FiMax: integer;
    Foption: string;
    Fi: integer;
    { Private declarations }
  protected
    procedure Execute; override;
    procedure AddItem();
  public
    constructor create(iMax: integer; option: string);
  end;

implementation

{ ThreadT1 }

procedure ThreadT1.AddItem;
begin
  inc(Fi);
  Form1.ListBox1.Items.Add(format('item%s %d', [Foption, Fi]));
end;

constructor ThreadT1.create(iMax: integer; option: string);
begin
  FiMax := iMax;
  Foption := option;
  FreeOnTerminate := true;
  inherited create(false);
end;

procedure ThreadT1.Execute;
var
  i: integer;
begin
  if WaitForSingleObject(hMutex, INFINITE) = WAIT_OBJECT_0 then
    for i := 0 to fimax - 1 do
    begin
      sleep(50);
      Synchronize(AddItem)
    end;
  ReleaseMutex(hMutex);
end;

{ ThreadT2 }

procedure ThreadT2.AddItem;
begin
  inc(Fi);
  Form1.ListBox1.Items.Add(format('item%s %d', [Foption, Fi]));
end;

constructor ThreadT2.create(iMax: integer; option: string);
begin
  FiMax := iMax;
  Foption := option;
  FreeOnTerminate := true;
  inherited create(false);
end;

procedure ThreadT2.Execute;
var
  i: integer;
begin
  for i := 0 to FiMax - 1 do
  begin
    sleep(50);
    Synchronize(AddItem)
  end;
end;

end.