请您解答:delphi多线程例程
liyue 2000-07-08 08:54:00 我在本网的delphi开发文章中看到《delphi32下的多线程程序设计》一文。但其给的例程无法运行,我已经“研究”了一夜,头都“大”了,请大虾指点。谢谢!一定要将程序在您的计算机上运行通过,然后照原样贴上来。我是初级水平,无法辨认任何“打印错误”。谢谢!例程如下:
这是一个多线程的碰碰球游戏,你可以有多个不同的球,它们分属不同的线程,各自独立的在屏幕上碰撞。显然,由于多个球运行的显示会同时操作vcl资源,为了安
全,我们在execute过程中的执行部分加入了synchronize(moveshape)来调用moveshape过程,实际上,在任何需要操作vcl资源的地方,例如窗体、位图,都应加入synchronize调用。
unit bncthrd;
interface
uses
winprocs,classes,graphics,extctrls;
type
tbouncethread=class(tthread)
private
fshape:tshape;
fxspeed:integer;
fyspeed:integer;
procedure moveshape;
protected
procedure execute;override;
public
constructor create(suspended:boolean;shape:tshape;xspeed,yspeed:integer);
propertyshape:tshapereadfshape;
end;
implementation
procedure tbouad.moveshape;
var
maxheight,maxwidth:integer;
begin
with fshape do
begin
left:=left+fxspeed;
top:=top+fyspeed;
if(left=0) or(left+width=parent.width)then
fxspeed:=fxspeed*-1;
if(top=0)or(top=height+parent.height)then
fyspeed:=fyspeed*-1;
end;
end;
procedure tbouncethread.execute;
begin
while not terminated do
begin
synchronize(moveshape);
end;
end;
constructor tbouncethread.create(suspended:boolean;shape:tshape;
xspeed,yspeed:integer);
begin
inherited create(suspended);
fshape:=shape;
fxspeed:=xspeed;{x轴走向的速度}
fyspeed:=yspeed;{y轴走向的速度}
freeonterminate:=true;
end;
end.
执行时我们可以新建一个程序,然后在uses部分加入以上的bncthrd单元,再在它的窗体form1上加入两个shape控件shape1和shape2,shape1可以是一个矩形而shape2
是一个圆。加入以下的代码就可以让矩形和圆动起来。
unit Unit1;
interface
uses
bncthrd,Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TForm1 = class(TForm)
Shape1: TShape;
Shape2: TShape;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
tbouncethread.create(false,shape1,1,2);
tbouncethread.create(false,shape2,2,3);
end;
end.