给你刚弄的一个例子:
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);
procedure Timer1Timer(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');
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;
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
//WAIT_OBJECT_0 指定的对象处于发信号状态;
for i := 0 to fimax - 1do
// 调用WaitForSingleObject()函数的线程就成为该互斥对象的拥有者,此互斥对象设为不发信号状态。
begin
sleep(50);
Synchronize(AddItem)
end;
ReleaseMutex(hMutex);
//复位 重新进入发信号状态
end;
end.