初学多线程的一个小问题(100分)

  • 主题发起人 liersbaby
  • 开始时间
L

liersbaby

Unregistered / Unconfirmed
GUEST, unregistred user!
比如我的MyThread有个procedure MyProc(i:integer),他的任务就是将i的内容写到一个ListBox中,我希望同时创建10个线程,然后每个线程就往listbox里面写自己对应的那个i,怎么写,讲讲思路,给个程序框架,谢谢
 
type
MyThread=Class(TThread)
public
contructor create(Sender: TListBox);
....
end;

你的难题就是如何将TListBox传入线程对象,但用syncronize函数却不支持
MyProc(i:integer;LB:TListbox)这种用法。在你的线程类的构造函数中传入
TListBox,问题就可以解决啦。
 
如此把i做成TMyThread的成员变量,将MyProc在参数去掉即可在Execute中使用Synchronize(MyProc)方式调用。
 
1.定义的线程中有一个成员变量FListBox、FIndex和FInteger,FListBox是你要操作的那个
TListBox;FIndex是线程在ListBox中的序号;FInteger是你在操作的变量;
2.在线程的Create构造过程中写:
constructor TMyThread.Create(ListBox: TListBox);
begin
FInteger := 0;//对应于你过程中的i
FListBox := ListBox;
FIndex := FListBox.Items.AddObject('0', Self);//在线程还没有执行的时候取得序号
inherited Create(False);
end;
3.在线程中还有一个过程:
procedure TMyThread.ModifyInteger;
begin
FInteger := .....//按照你以前的设想操作为个变量
FListBox.Items[FIndex] := IntToStr(FInteger);//修改该项
end;
4.在线程的Execute过程中写:
procedure TMyThread.Execute;
begin
...
Synchronize(ModifyInteger);
...
end;
 
顶部