前面的例子都是让若干线程做同样的事情, 下面这个例子中的三个线程将分别在三个画板上随机画不同颜色的椭圆.
接下来的很多事情我想要基于这个例子来做.
本例效果图:
代码文件:
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}
var
h1,h2,h3: THandle;
{第一个线程的入口函数: 画红色椭圆}
function ThreadFun1(p: Pointer): Integer; stdcall;
var
i, x1,y1,x2,y2: Integer;
begin
Form1.PaintBox1.Canvas.Brush.Color := clRed;
for i := 0 to 50000 do with Form1.PaintBox1 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(0);
end;
Result := 0;
end;
{第二个线程的入口函数: 画绿色椭圆}
function ThreadFun2(p: Pointer): Integer; stdcall;
var
i, x1,y1,x2,y2: Integer;
begin
Form1.PaintBox2.Canvas.Brush.Color := clGreen;
for i := 0 to 50000 do with Form1.PaintBox2 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(0);
end;
Result := 0;
end;
{第三个线程的入口函数: 画蓝色椭圆}
function ThreadFun3(p: Pointer): Integer; stdcall;
var
i, x1,y1,x2,y2: Integer;
begin
Form1.PaintBox3.Canvas.Brush.Color := clBlue;
for i := 0 to 50000 do with Form1.PaintBox3 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(0);
end;
Result := 0;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ID: DWORD;
begin
h1 := CreateThread(nil, 0, @ThreadFun1, nil, 0, ID);
h2 := CreateThread(nil, 0, @ThreadFun2, nil, 0, ID);
h3 := CreateThread(nil, 0, @ThreadFun3, nil, 0, ID);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
CloseHandle(h1);
CloseHandle(h2);
CloseHandle(h3);
end;
end.