16,748
社区成员
发帖
与我相关
我的任务
分享
//线程类
unit Unit2;
interface
uses
Classes,sysutils,SyncObjs,Dialogs;
type
TTest = class(TThread)
private
{ Private declarations }
FSum:Integer;
procedure UpdateCaption;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean);
end;
implementation
uses Unit1;
procedure TTest.UpdateCaption;
begin
Form1.Edit1.Text := Inttostr(FSum);
showmessage('Sum Process End');
end;
procedure TTest.Execute;
begin
//必须循环来判断Terminated标志
while not Terminated do
begin
FSum:=FSum+1;//这里可以执行其它独立的任务,例如生成带有独立任务的线程
case QuitEvent.WaitFor(60*100) of //阻塞时间,即Timer.Interval
wrSignaled, wrAbandoned: Terminate;
end;
Synchronize(UpdateCaption);//实现问题2,把函数放在这里,是为了更直观地看到当前执行的结果
end;
{ Place thread code here }
end;
constructor TTest.Create(CreateSuspended: Boolean);
begin
inherited;
FSum:=0;
end;
end.
//主线程代码
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,SyncObjs;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure NotifySumThreadsToQuit;
var
Form1: TForm1;
QuitEvent: TEvent;//事件说白了就是一个全局的布尔变量,用SetEvent置为一种状态,便于在线程循环时根据该标识来将线程中止
implementation
uses Unit2;
{$R *.dfm}
procedure NotifySumThreadsToQuit;
begin
QuitEvent.SetEvent;//置信号
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Thd:TTest;
begin
Thd:=TTest.Create(True);
Thd.FreeOnTerminate:=False;
Thd.Resume;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
NotifySumThreadsToQuit//通知线程结束
end;
initialization
QuitEvent := TEvent.Create(nil,true,false,'SumProcessEnd');//创建事件
finalization
QuitEvent.Free;//释放事件
end.
type
TMyThread = class(TThread)
private
FTimer:TTimer;
procedure TimerProc(Sender: TObject);
protected
procedure Execute;override;
public
constructor Create;override;
procedure KillIt;//结束
end;
implementation
procedure TMyThread.TimerProc(Sender: TObject);
begin
...
end;
procedure TMyThread.KillIt;
begin
PostThreadMessage(ThreadNo,WM_QUIT,0,0);
end;
procedure TMyThread.Execute;
begin
FTimer:=TTimer.Create(nil);
try
FTimer.Enabled:=false;//需要用的时候Enabled设置为True即可。
FTimer.OnTimer:=TimerProc;
while GetMessage(MsgRec, 0, 0, 0) do begin
TranslateMessage(MsgRec);
DispatchMessage(MsgRec)
end;
Terminate;
finally
FTimer.Free;
end;
end;