我认为您必须显示您的重启代码?因为据我所知,如果线程完成它的 Execute 过程,那么它在操作系统中的状态将更改为 DONE 并且再次调用 resume 只会启动该线程,因为它只是主线程中的一个函数,而不是一个真正的单独线程。
顺便说一句,您可以根据需要使用此示例代码
unit UWorker;
interface
uses Windows, Classes, Contnrs;
type
TWorkerThread=class;
TWorkerJob=class
procedure ExecuteJob(Worker: TWorkerThread); virtual; abstract;
end;
TWorkerThread=class(TThread)
private
FFinished: TObjectList;
FNotFinished: TObjectList;
protected
procedure Execute;Override;
public
constructor Create(createSuspended: Boolean);override;
destructor Destroy; override;
public
property Finished: TObjectList read FFinished;
property NotFinished: TObjectList read FNotFinished;
end;
implementation
{ TWorkerThread }
constructor TWorkerThread.Create(createSuspended: Boolean);
begin
inherited;
FFinished := TObjectList.Create;
FNotFinished := TObjectList.Create;
end;
destructor TWorkerThread.Destroy;
begin
FFinished.Free;
FNotFinished.Free;
inherited;
end;
procedure TWorkerThread.Execute;
var
CurrentJob: TWorkerJob;
begin
while not Terminated do
begin
if FNotFinished.Count > 0 then
begin
CurrentJob := TWorkerJob(FNotFinished.Items[0]);
FNotFinished.Extract(CurrentJob);
with CurrentJob do
begin
ExecuteJob(Self);
end;
FFinished.Add(CurrentJob);
end else
begin
// pass the cpu to next thread or process
Sleep(5);
end;
end;
end;
end.
要使用此代码,只需创建一个工作人员,然后创建一些作业实例并将它们添加到 NotFinished 列表中。Worker 会一一执行所有作业。要重新启动作业,只需从已完成列表中提取它并再次将其添加到未完成。
请记住,您必须继承您的作业并覆盖 ExecuteJob 过程。