多线程提问,create里的参数好像没用的阿?

sulemon 2004-08-11 03:37:26
以下是我的测试程序,是希望输出以下结果
1
2
1
2
3
但实际运行过程中,得输出结果却是
1
2
3
1
2
3 也就是说,后一个创建的线程运行了两次,请问各位,为什么会这样呢??有什么办法能让一个线程结束后才让后一个线程运行呢??? 多些指教。。。。。

type
Tmythread = class(Tthread)
protected
procedure execute; override;
public
constructor create(i:integer);
procedure shownumber;
end;

var
Form1: TForm1;
count:integer;
implementation

{$R *.dfm}

procedure Tmythread.execute;
begin
synchronize(shownumber);
end;

procedure Tmythread.shownumber;
var j:integer;
begin
for j:=1 to count do
begin
form1.Memo1.Lines.Add(inttostr(j)) ;
sleep(2);
end;
end;

constructor Tmythread.create(i:integer);
begin
freeonterminate:=true;
inherited create(true);
count:=i;
resume;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
Tmythread.create(2);
Tmythread.create(3);
end;
...全文
112 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
postren 2004-08-16
  • 打赏
  • 举报
回复
也可以用临界区,第一个线程先进入临界区,第二个线程只能等第一个线程结束后才能进入该临界区,所以,在第一个线程结束之前,第二个线程只能等待
sulemon 2004-08-11
  • 打赏
  • 举报
回复
楼上两位正解,多谢拉。。。。
xyqxj 2004-08-11
  • 打赏
  • 举报
回复
type
Tmythread = class(Tthread)
protected
count:integer;
procedure execute; override;
public
constructor create(i:integer);
procedure shownumber;
end;
xyqxj 2004-08-11
  • 打赏
  • 举报
回复
在线程类定义count可以解决你的问题,不要使用全局变量

1,593

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 网络通信/分布式开发
社区管理员
  • 网络通信/分布式开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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