16,748
社区成员
发帖
与我相关
我的任务
分享
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TPaintThread1 = class(TThread)
private
X, Y:Integer;
{ Private declarations }
protected
procedure Execute; override;
procedure Paint1;
end;
TForm1 = class(TForm)
btn1: TButton;
img1: TImage;
img2: TImage;
btn2: TButton;
btn3: TButton;
btn4: TButton;
tmr1: TTimer;
procedure btn1Click(Sender: TObject);
procedure btn2Click(Sender: TObject);
procedure btn4Click(Sender: TObject);
procedure tmr1Timer(Sender: TObject);
procedure btn3Click(Sender: TObject);
private
{ Private declarations }
public
PT1:TPaintThread1;
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{Thread1}
procedure TPaintThread1.Paint1;
begin
Form1.img1.Canvas.Pixels[X, Y]:=clRed;
end;
procedure TPaintThread1.Execute;
begin
Randomize;
repeat
X:=Random(105);
Y:=Random(105);
Synchronize(Paint1);
until Terminated;
end;
procedure TForm1.btn1Click(Sender: TObject);
begin
PT1:=TPaintThread1.Create(False);
end;
procedure TForm1.btn2Click(Sender: TObject);
begin
if btn2.Caption='继续' then
begin
PT1.Resume;
btn2.Caption:='暂停';
end
else begin
btn2.Caption:='继续';
PT1.Suspend;
end;
end;
procedure TForm1.btn3Click(Sender: TObject);
begin
Randomize;
tmr1.Enabled:=True;
end;
procedure TForm1.btn4Click(Sender: TObject);
begin
if btn4.Caption='继续' then
begin
tmr1.Enabled:=True;
btn4.Caption:='暂停';
end
else begin
btn4.Caption:='继续';
tmr1.Enabled:=False;
end;
end;
procedure TForm1.tmr1Timer(Sender: TObject);
begin
img2.Canvas.Pixels[Random(105),Random(105)]:=clBlack;
end;
end.
procedure TPaintThread2.Paint2;
begin
Form1.img2.Canvas.Lock;
Form1.img2.Canvas.Pixels[X2, Y2]:=clBlack;
Form1.img2.Canvas.UnLock;
end;
procedure TPaintThread2.Execute;
var
tmp:Cardinal;
begin
Randomize;
repeat
tmp:=GetTickCount;
if (GetTickCount-tmp)>=10 then
begin
X2:=Random(105);
Y2:=Random(105);
tmp:=GetTickCount;
try
EnterCriticalSection(CriticalSection); //进入临界区
Paint2;
finally
LeaveCriticalSection(CriticalSection); //离开临界区
end;
end;
until Terminated;
end;