多線程編程(18)

來源:互聯網
上載者:User

前面的例子都是讓若干線程做同樣的事情, 下面這個例子中的三個線程將分別在三個畫板上隨機畫不同顏色的橢圓.

接下來的很多事情我想要基於這個例子來做.

本例效果圖:

代碼檔案:

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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.