线程停止问题

qlonsh 2010-01-16 09:14:10
procedure TForm1.Button1Click(Sender: TObject);  //开始
begin
thread:=bb.Create(false);
end;

procedure TForm1.Button2Click(Sender: TObject); //停止
begin
thread.Free;
thread.Terminate
end;
我在完成第第三个步聚时按停止操作时,线程能完全停止,而是在从步聚一按停止时,线程并没有完成停止,而是再再执行下一步聚才能完全停止;请问如何解决。
下面是线程的内容:
procedure bb.Execute;
var
i:integer;
begin
i:=0;
while not Terminated do
begin
form1.Memo1.Lines.Add('1:'+inttostr(i));  //步聚一
i:=i+1;
if terminated=true then exit;
sleep(5000);

form1.Memo1.Lines.Add('2:'+inttostr(i)); //步聚二
i:=i+1;
if terminated=true then exit;
sleep(3000);

form1.Memo1.Lines.Add('3:'+inttostr(i)); //步聚三 
i:=i+1;
if terminated=true then exit;
sleep(3000)

end;
end;
...全文
161 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wooden954 2010-01-16
  • 打赏
  • 举报
回复
2、3楼正确。
需要检测Terminated的状态
kfcoffe 2010-01-16
  • 打赏
  • 举报
回复
分析程序执行流程:
你在步聚三 按停止操作时,接下来程序会继续循环从而就会执行while not Terminated do 到这里就会退出(因为你停止操作就是把Terminated 置为真)。

你在步聚一 按停止操作时,接下来会执行步骤二,三。在这之后才会检测线程是否退出条件while not Terminated do 这也就是你上面说的那种情况。


要实现你说的:

procedure bb.Execute;
var
i:integer;
begin
i:=0;
while not Terminated do
begin
form1.Memo1.Lines.Add('1:'+inttostr(i));  //步聚一
i:=i+1;
if terminated=true then exit;
sleep(5000);
if Terminated then Exit; //不断的检测
form1.Memo1.Lines.Add('2:'+inttostr(i)); //步聚二
i:=i+1;
if terminated=true then exit;
sleep(3000);
if Terminated then Exit; //不断的检测
form1.Memo1.Lines.Add('3:'+inttostr(i)); //步聚三 
i:=i+1;
if terminated=true then exit;
sleep(3000)

end;
end;



麦客来了 2010-01-16
  • 打赏
  • 举报
回复
1. Button1中创建的线程类使用false参数,是当线程类bb的实例创建后立即执行。
2. 在步骤一附件点击,实际上if terminated=true then exit;已经执行,这里terminated = false,执行sleep函数, sleep执行完成后,terminated = true,继续执行步骤二,执行到if terminated=true 判断时,条件成立,退出
3. 直接在步骤三执行时,terminated在sleep(3000)完成后被设置成true,然后进行while判断,while条件判断不成立,循环结束。
tjj5203 2010-01-16
  • 打赏
  • 举报
回复
帮楼主顶下,我也想知道

5,388

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧