學習TTHREAD的用法,照著寫,但是結果好像只輸出了最后一個執行緒
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
ListBox1: TListBox;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure AddLogInfo(rybh: string);
public
{ Public declarations }
end;
TMyThread = class(TThread)
private
str: string; //日志資訊
procedure AddLog; //添加日志
public
procedure Execute; override;
end;
var
Form1: TForm1;
sl:Integer;
Strlog:string;
implementation
{$R *.dfm}
procedure TForm1.AddLogInfo(rybh: string);
begin
Form1.ListBox1.Items.Add('回傳值:'+rybh);
end;
procedure TMyThread.Execute;
var
i: Integer;
begin
FreeOnTerminate := True; {這可以讓執行緒執行完畢后隨即釋放}
i:=sl;
Str:='D'+inttostr(I);
StrLog:=Str;
synchronize(AddLog); //發送成功給捕捉
end;
procedure TMyThread.AddLog;
begin
Form1.AddLogInfo(StrLog);
end;
procedure TForm1.Button1Click(Sender: TObject);
var ib: Integer;
begin
ib:=0;
while ib<10 do
begin
sl:=ib;
TMyThread.Create(False);
sleep(50);
ib:=ib+1;
end;
end;
end.
uj5u.com熱心網友回復:
10個執行緒有跑起來,只是你的引數在Button1Click事件中已經運行到9了,所以在ListBox1中顯示的都是10個D9代碼修改
TMyThread = class(TThread)
private
str: string; //日志資訊
procedure AddLog; //添加日志
public
constructor Create(const i:Integer);
procedure Execute; override;
end;
constructor TMyThread.Create(const i: Integer);
begin
inherited Create(true);//Suspend為真,立即被懸掛
FreeOnTerminate := True; {這可以讓執行緒執行完畢后隨即釋放}
str:='D'+inttostr(i);
end;
procedure TMyThread.Execute;
begin
synchronize(AddLog); //發送成功給捕捉
end;
procedure TMyThread.AddLog;
begin
Form1.AddLogInfo(str);
end;
procedure TForm1.Button2Click(Sender: TObject);
var ib: Integer;
a:TMyThread;
begin
ib:=0;
while ib<10 do
begin
ib:=ib+1;
a:=TMyThread.Create(ib);
a.Resume;
sleep(200);
end;
end;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/64642.html
標籤:網絡通信/分布式開發
