~~菜鸟提问,有关多线程的~~
两个Memo,分别由两个线程控制,一个Memo循环输出1到10,每个数之间延迟1秒{sleep(1000)},另一个Memo循环输出11到20,每个数之间也延迟1秒,如何实现?以下是小弟写的,编译后点开始运行程序有误,麻烦高手看看
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Unit2, Unit3;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Memo2: TMemo;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
memo1.Clear;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Memo1Thread: TMemo1Thread;
begin
Memo1Thread:= TMemo1Thread.Create(False);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
close;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
Memo2Thread: TMemo2Thread;
begin
Memo2Thread:= TMemo2Thread.Create(False);
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
close;
end;
end.
------------------------------------------------------------
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TMemo1Thread = class(TThread)
Memo1: TMemo;
private
{ Private declarations }
protected
procedure Execute; override;
end;
implementation
{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TMemo1Thread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ TMemo1Thread }
procedure TMemo1Thread.Execute;
var
i:integer;
s:string;
begin
s:='';
for i:=1 to 10 do
begin
s:=inttostr(i);
memo1.Lines.Add(s);
sleep(1000);
end;
end;
end.
--------------------------------------------------------------
unit Unit3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TMemo2Thread = class(TThread)
Memo2: TMemo;
private
{ Private declarations }
protected
procedure Execute; override;
end;
implementation
{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TMemo2Thread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ TMemo2Thread }
procedure TMemo2Thread.Execute;
var
m:integer;
n:string;
begin
n:='';
for m:=11 to 20 do
begin
n:=inttostr(m);
memo2.Lines.Add(n);
sleep(1000);
end;
end;
end.