Home > Back-end >  Help: DELPHI multithreading
Help: DELPHI multithreading

Time:09-22

Learning the use of the TTHREAD, according to write, but the result seems to be only output the last thread
The unit Unit1;

Interface

USES the
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

Type
TForm1=class (TForm)
ListBox1: TListBox;
For: TButton;
Button2: TButton;
Procedure Button1Click (Sender: TObject);

Private
{Private declarations}
Procedure AddLogInfo (rybh: string);
Public
{Public declarations}
end;

TMyThread=class (TThread)
Private
STR: string;//log information
Procedure AddLog;//add log
Public

Procedure the Execute; Override.
end;

Var
Form1: TForm1;
Sl: Integer;
Strlog: string;



Implementation

{$R *. DFM}
Procedure TForm1. AddLogInfo (rybh: string);
The begin

Form1. ListBox1. Items. The Add (' return values: '+ rybh);

end;

Procedure TMyThread. Execute;
Var
I: Integer;
The begin
FreeOnTerminate:=True; {this allows threads execute immediately after the release}
I:=sl;
Str:='D' + inttostr (I);
StrLog:=Str;
The synchronize (AddLog);//send successfully to capture
end;

Procedure TMyThread. AddLog;
The begin
Form1. AddLogInfo (StrLog);
end;



Procedure TForm1. Button1Click (Sender: TObject);
Var ib: Integer;
The begin
The ib:=0;
While ib<10 do
The begin
Sl:=the ib;
TMyThread. Create (False);
Sleep (50);
Ib:=ib + 1;
end;
end;

End.

CodePudding user response:

10 threads running, too, but your parameters in the event of an Button1Click already run to 9, so in the show in the ListBox1 is 10 D9
Code change

TMyThread=class (TThread)
Private
STR: string;//log information
Procedure AddLog;//add log
Public
The constructor Create (const I: Integer);
Procedure the Execute; Override.
end;


The constructor TMyThread. Create (const I: Integer);
The begin
Inherited the Create (true);//Suspend is true, was immediately suspended
FreeOnTerminate:=True; {this allows threads execute immediately after the release}
STR:='D' + inttostr (I);
end;

Procedure TMyThread. Execute;
The begin
The synchronize (AddLog);//send successfully to capture
end;

Procedure TMyThread. AddLog;
The begin
Form1. AddLogInfo (STR);
end;

Procedure TForm1. Button2Click (Sender: TObject);
Var ib: Integer;
A: TMyThread;
The begin
The ib:=0;
While ib<10 do
The begin
Ib:=ib + 1;
A:=TMyThread. Create (ib);
A.R esume;
Sleep (200);
end;
end;
  • Related