unit Unit1;

interface

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

type
  TMyThread = class(TThread)
    private
    FNum:Integer;
    protected
      procedure Execute;override;
      procedure Run;
      procedure SetNum(Value:integer);  {设置Num}
      function GetNum:integer;          {获取Num}
      constructor Create(Aswith:Boolean;ANum:Integer);  {给创建方法添加一个参数用于传递}
    public
  end;

  TForm1 = class(TForm)
    pb1: TPaintBox;
    pb2: TPaintBox;
    pb3: TPaintBox;
    btn1: TButton;
    procedure btn1Click(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses SyncObjs;

const
   colors:array[0..2] of TColor =(clRed,clGreen,clBlue);

var
  MyThread:TMyThread;
  paintArr:array[0..2] of TPaintBox;
//  MyThreadArr:array[0..2] of TMyThread;  {也可用数组多个线程进行}
  Mutex:TMutex;


procedure TForm1.btn1Click(Sender: TObject);
var
  i:integer;
begin
  if Assigned(Mutex) then Mutex.Free;   {如果存在,先释放}
  Mutex:=TMutex.Create(False);           {创建互斥体,参数为创建者先不占用}
  Repaint;                               {重画窗体}
  paintArr[0]:=pb1;                       {把PaintBox1给数组paintArr[0]}
  paintArr[1]:=pb2;
  paintArr[2]:=pb3;
  for i := Low(paintArr )to High(paintArr) do
  begin
    MyThread:=TMyThread.Create(False,i);  {如果声明了线程数组类,可以在这里一起做循环多个线程操作}
  end;
end;

{ TMyThread }



constructor TMyThread.Create(ASwith: Boolean; ANum: Integer);
begin
  inherited Create(Aswith);   {继承并传参}
  SetNum(ANum);               {设置字段Num}
end;

procedure TMyThread.Execute;
begin
  inherited;
  FreeOnTerminate:=True;
  Run;
end;

function TMyThread.GetNum: integer;
begin
  Result:=FNum;
end;

procedure TMyThread.Run;
var
  i,n,x1,x2,y1,y2:integer;
begin
  n:=GetNum;
  paintArr[n].Color:=Colors[n];
  for i := 0 to 200 do
  begin
    if Mutex.WaitFor(INFINITE)=wrSignaled then  {判断互斥体有没有被占用}
    begin
      with paintArr[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;
    end;
    Mutex.Release;  {释放放这里为每进行一次,释放,谁拿到谁用}
  end;
//   Mutex.Release;  {释放放这里为每进行一轮循环,释放,相当于排队进行}
end;

procedure TMyThread.SetNum(Value: integer);
begin
  FNum:=Value;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  Mutex.Free;
end;

end.