我按照两位说的.写了如下的东西,改了一个例子
unit Umulti;
interface
uses
Windows, Messages,UfindThread, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,ComCtrls;
type
TMultiFind = class(TThread)
private
SearchThreads: Array of TThread ;
{ Private declarations }
protected
Progr:integer;
Finders:Array[1..4]of TFindThread;
Procedure UpdateProgress;
Procedure show;
procedure Execute;
override;
Procedure StopAllThreads;
Public
LookFor,OutPut:string;
Progress:array[1..5]of TProgressBar;
end;
const
SearchThread_Count=4;
implementation
uses Uform;
{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TMultiFind.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
}
{ TMultiFind }
Procedure TMultiFind.UpdateProgress ;
begin
Application.ProcessMessages;
Progress[1].Position :=Progr;
end;
procedure TMultiFind.show;
begin
ShowMessage(Output);
end;
Procedure TMultifind.StopAllThreads ;
var
MultiThread:TThread;
i:integer;
begin
for i:=1 to SearchThread_countdo
begin
MultiThread:=Finders;
MultiThread.Terminate;
end;
for i:=1 to 4do
begin
MultiThread:=Finders;
MultiThread.waitfor;
end;
end;
procedure TMultiFind.Execute;
var
//Finders:Array[1..4]of TFindThread;
MultiThread:TThread;
i,j:integer;
begin
Setlength(SearchThreads,SearchThread_count);
for I:=1 to SearchThread_countdo
begin
if Terminated then
exit;
Finders:=TFindThread.Create(true);
Finders.LookFor:=LookFor;
Finders.Progress :=Progress[I+1];
Finders.FreeOnTerminate:=true;
Finders.Resume;
end;
//wait the Threads to end.
..
for j:=1 to 4do
begin
{ if Terminated then
//如果不用suspend,就这样用括号种的代码
begin
for i:=1 to SearchThread_countdo
begin
MultiThread:=Finders;
MultiThread.Terminate;
end;
for i:=1 to 4do
begin
MultiThread:=Finders;
MultiThread.waitfor;
end;
exit;
end;
}
//---------------------------------
Finders[j].WaitFor;
//如果有这句,父线程要等它的子线程运行结束才能运行下面的语句
Progr:=j;
synchronize(UpdateProgress);
end;
suspend;
//好像没有起作用是不是我写错了
stopallThreads;
//show the Result
Output:='Found:';
for I:=1 to 4do
Output:=output+Format('%s NO is %d,',
[LookFor,Finders.Found]);
Synchronize(show);
end;
end.
//---------------------------终止线程的调用--------------
procedure TForm1.Button3Click(Sender: TObject);
var i:integer;
begin
{MainThread.Suspend ;
MainThread.Terminate ;
While WaitforSingleObject(MainThread.Handle,0)<>WAIT_OBJECT_0do
for i:=0 to 10do
Application.ProcessMessages ;
MainThread.Free;
} //如果用括号种的代码时,可以让所有的子线程停止,但是无法终止
//MainThread.Free这句无法执行,一直在处理Messages
MainThread.Resume;
end;
谁要源码,帮我调试一下,感激不尽