delphi线程的创建、挂起、激活与终止

procedure TForm1.Button1Click(Sender: TObject);
begin
//创建线程,同时线程函数被调用
hthread:=CreateThread(nil,0,@MyThreadfunc,nil,0,ThreadID);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
SuspendThread(hThread); //挂起线程
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
ResumeThread(hThread); // 激活线程
end;

procedure TForm1.Button4Click(Sender: TObject);
begin
TerminateThread(hThread,0); // 终止线程
end;

注意 当T T h r e a d的C r e a t e ( )被调用时,需要传递一个布尔型的参数C r e a t e S u s p e n d e d。如果把这
个参数设成F a l s e,那么当调用C r e a t e ( )后,E x c u t e ( )会被自动地调用,也就是自动地执行线程代
码。如果该参数设为Tr u e,则需要运行T T h r e a d的R e s u m e ( )来唤醒线程。一般情况下,当你调
用C r e a t e ( )后,还会有一些其他的属性要求设置。所以,应当把C r e a t e S u s p e n d e d参数设为Tr u e,
因为在TThread已执行的情况下设置TThread的属性可能会引起麻烦。

挂起和唤醒线程
回顾本章在先前学习TThread 的构造器C r e a t e ( )时讲过,当创建一个线程时,可以先使它处于挂起
状态,在调用了R e s u m e ( )唤醒线程后再执行线程代码。你可能已经想到,对线程可以调用 S u s p e n d ( )和
R e s u m e ( )来动态地挂起或唤醒。

原文地址:https://www.cnblogs.com/linguoqiu/p/2855917.html