Delphi多线程测试

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值