C
cgs1980
Unregistered / Unconfirmed
GUEST, unregistred user!
我想在主线程中启动一定数量的子线程,如 10 个子线程,如果某一个子线程运行完毕,那么就通知主线程再启动一个新的子线程(主线程想知道是哪个子线程运行完毕),由此使子线程的数量保持在 10 个左右,我使用下面的方法,但启动新的子线程时会出错,试了好多次都不行,敬请大家指教,同时我想知道在delphi中子线程运行完毕之后通知主线程是否有更好的方法?
代码:
unit ThreadsDemo;
type
TMainThread = class(TThread)
private
str: string;
SubThreadList: TList;
//线程列表
procedure CreateNewSubThread(Sender: TObject);//创建新线程
protected
procedure Execute;
override;
public
constructor Create(str: string);
end;
TSubThread = class(TThread)
private
FStr: string;
functiondo
SomeThings(str: string): boolean;
protected
procedure Execute;
override;
public
constructor Create(str: string);
end;
var
ThreadsArray: array of TSubThread // 定义线程数组
counter: Integer;
//线程计数
procedure TMainThread.Execute;
var
i: Integer;
begin
counter:= 0;
SubThreadList := TList.Create;
SetLength(ThreadsArray,10);
// 动态设置线程的数量
for i := 0 to 9do
begin
ThreadsArray[i] := TSubThread.Create(str);
ThreadsArray[i].OnTerminate := CreateNewSubThread;
SubThreadList.Add(ThreadsArray[i]);
Inc(counter);
end;
end;
procedure TMainThread.CreateNewSubThread(Sender: TObject);
var
Index: integer;
begin
if counter > 100 then
exit;
//[red]在list中查找刚才的线程对象, 为什么在这里会出错?[/red]
Index:=SubThreadList.IndexOf(Sender);
SubThreadList.Delete(Index);
ThreadsArray[index] := TSubThread.Create(str);
ThreadsArray[index].OnTerminate := CreateNewSubThread;
SubThreadList.Add(ThreadsArray[i]);
Inc(counter);
end;
procedure SubThreadList.Execute;
begin
do
SomeThings(FStr);
end;
end.