第一個例子的代碼文件(窗體同上):
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
PaintBox1: TPaintBox;
PaintBox2: TPaintBox;
PaintBox3: TPaintBox;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
const
colors: array[0..2] of TColor = (clRed, clGreen, clBlue);
var
hArr: array[0..2] of THandle;
panitArr: array[0..2] of TPaintBox;
hMutex: THandle; {互斥對象的句柄}
function ThreadFun(p: Pointer): Integer; stdcall;
var
i,n,x1,y1,x2,y2: Integer;
begin
n := Integer(p);
panitArr[n].Color := colors[n];
if WaitForSingleObject(hMutex, INFINITE) = WAIT_OBJECT_0 then
begin
for i := 0 to 50 do with panitArr[n] do
begin
x1 := Random(Width); y1 := Random(Height);
x2 := Random(Width); y2 := Random(Height);
Canvas.Lock;
Canvas.Ellipse(x1,y1,x2,y2);
Canvas.Unlock;
Sleep(10);
end;
ReleaseMutex(hMutex);
end;
Result := 0;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ID: DWord;
i: Integer;
begin
panitArr[0] := PaintBox1;
panitArr[1] := PaintBox2;
panitArr[2] := PaintBox3;
CloseHandle(hMutex);
hMutex := CreateMutex(nil, False, nil);
for i := 0 to Length(hArr) - 1 do
hArr[i] := CreateThread(nil, 0, @ThreadFun, Ptr(i), 0, ID);
end;
procedure TForm1.FormDestroy(Sender: TObject);
var
i: Integer;
begin
CloseHandle(hMutex);
for i := 0 to Length(hArr) - 1 do CloseHandle(hArr[i]);
end;
end.