在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
再做个实例总结下: 用多线程类实现,在三个PaintBox上画椭圆。 1 unit Unit1; 2 3 interface 4 5 uses 6 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 7 Dialogs, StdCtrls, ExtCtrls; 8 9 type 10 TMyThread = class(TThread) 11 private 12 FNum:Integer; 13 protected 14 procedure Execute;override; 15 procedure Run; 16 procedure SetNum(Value:integer); {设置Num} 17 function GetNum:integer; {获取Num} 18 constructor Create(Aswith:Boolean;ANum:Integer); {给创建方法添加一个参数用于传递} 19 public 20 end; 21 22 TForm1 = class(TForm) 23 pb1: TPaintBox; 24 pb2: TPaintBox; 25 pb3: TPaintBox; 26 btn1: TButton; 27 procedure btn1Click(Sender: TObject); 28 procedure FormDestroy(Sender: TObject); 29 private 30 { Private declarations } 31 public 32 { Public declarations } 33 end; 34 35 var 36 Form1: TForm1; 37 38 implementation 39 40 {$R *.dfm} 41 42 uses SyncObjs; 43 44 const 45 colors:array[0..2] of TColor =(clRed,clGreen,clBlue); 46 47 var 48 MyThread:TMyThread; 49 paintArr:array[0..2] of TPaintBox; 50 // MyThreadArr:array[0..2] of TMyThread; {也可用数组多个线程进行} 51 Mutex:TMutex; 52 53 54 procedure TForm1.btn1Click(Sender: TObject); 55 var 56 i:integer; 57 begin 58 if Assigned(Mutex) then Mutex.Free; {如果存在,先释放} 59 Mutex:=TMutex.Create(False); {创建互斥体,参数为创建者先不占用} 60 Repaint; {重画窗体} 61 paintArr[0]:=pb1; {把PaintBox1给数组paintArr[0]} 62 paintArr[1]:=pb2; 63 paintArr[2]:=pb3; 64 for i := Low(paintArr )to High(paintArr) do 65 begin 66 MyThread:=TMyThread.Create(False,i); {如果声明了线程数组类,可以在这里一起做循环多个线程操作} 67 end; 68 end; 69 70 { TMyThread } 71 72 73 74 constructor TMyThread.Create(ASwith: Boolean; ANum: Integer); 75 begin 76 inherited Create(Aswith); {继承并传参} 77 SetNum(ANum); {设置字段Num} 78 end; 79 80 procedure TMyThread.Execute; 81 begin 82 inherited; 83 FreeOnTerminate:=True; 84 Run; 85 end; 86 87 function TMyThread.GetNum: integer; 88 begin 89 Result:=FNum; 90 end; 91 92 procedure TMyThread.Run; 93 var 94 i,n,x1,x2,y1,y2:integer; 95 begin 96 n:=GetNum; 97 paintArr[n].Color:=Colors[n]; 98 for i := 0 to 200 do 99 begin 100 if Mutex.WaitFor(INFINITE)=wrSignaled then {判断互斥体有没有被占用} 101 begin 102 with paintArr[n] do 103 begin 104 x1:=Random(Width);y1:=Random(Height); 105 x2:=Random(Width);y2:=Random(Height); 106 Canvas.Lock; 107 Canvas.Ellipse(x1,y1,x2,y2); 108 Canvas.Unlock; 109 Sleep(10); 110 end; 111 end; 112 Mutex.Release; {释放放这里为每进行一次,释放,谁拿到谁用} 113 end; 114 // Mutex.Release; {释放放这里为每进行一轮循环,释放,相当于排队进行} 115 end; 116 117 procedure TMyThread.SetNum(Value: integer); 118 begin 119 FNum:=Value; 120 end; 121 122 procedure TForm1.FormDestroy(Sender: TObject); 123 begin 124 Mutex.Free; 125 end; 126 127 end.
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论