多线程生成 1 到 1百万的数字
for i := 1 to 1000000 do
begin
lst1.Items.Add(IntToStr(i));
end;
这样很慢,我想用10个线程来生成;
可我只会用单线程;
type
TMyTThread = class(TThread)
private
{ Private declarations }
STR: string;
Tlist: TListBox;
procedure ToAdd;
protected
procedure Execute; override;
public
constructor Create(list: TListBox);
end;
type
TForm1 = class(TForm)
lst1: TListBox;
btn1: TButton;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
T1: TMyTThread;
implementation
{$R *.dfm}
procedure TForm1.btn1Click(Sender: TObject);
begin
T1 := TMyTThread.Create(lst1);
end;
{ TMyTThread }
constructor TMyTThread.Create(list: TListBox);
begin
Tlist := list; // 传递参数
FreeOnTerminate := True; // 自动删除
inherited Create(False); // 直接运行
end;
procedure TMyTThread.Execute;
var
I: Integer;
begin
for I := 1 to 1000000 do
begin
Application.ProcessMessages;
STR := IntToStr(I);
Synchronize(TOADD);
end;
end;
procedure TMyTThread.ToAdd;
begin
Tlist.Items.Add(STR);
end;
type
MyThread = class(TThread)
private
FListbox:TListbox;
Fi:Integer;
protected
procedure Execute;override;
public
constructor Create(lb:TListBox;i:Integer);
end;
type
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
a:Integer;
CS :TRTLCriticalSection;
implementation
{$R *.dfm}
constructor MyThread.Create(lb:TListBox;i:Integer);
begin
FListbox := lb;
Fi := i;
FreeOnTerminate := True;
inherited Create(True);
end;
procedure MyThread.Execute;
var
j:Integer;
begin
EnterCriticalSection(CS);
for j := Fi to a do
begin
FListbox.Items.Add(IntToStr(j));
end;
LeaveCriticalSection(CS);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Th1,th2:MyThread;
begin
a := 1000;
Th1 := MyThread.Create(ListBox1,0);
Th1.Resume;
Sleep(2000);
Application.ProcessMessages;
a := 2000;
Th2 := MyThread.Create(ListBox1,1001);
Th2.Resume;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
InitializeCriticalSection(CS);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
DeleteCriticalSection(cs);
end;