主要表格:
unit Unit3;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm3 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
class var counter : Integer;
end;
var
Form3: TForm3;
implementation
{$R *.dfm}
uses Unit4, Unit5;
procedure TForm3.Button1Click(Sender: TObject);
var
th1 : thCounter;
th2 : thPrinter;
begin
th1:= thCounter.Create;
th2:= thPrinter.Create;
end;
end.
线程计数器:
unit Unit4;
interface
uses
System.Classes, Unit3;
type
thCounter = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;
implementation
{ thCounter }
procedure thCounter.Execute;
var
i: Integer;
printVal : Integer;
begin
{ Place thread code here }
printVal:= 50;
for i := 0 to 1000000000 do
begin
Form3.counter:= i;
if Form3.counter = printVal then
begin
// RUN print thread ????
printVal:= printVal + 50;
end;
end;
end;
end.
线程打印:
unit Unit5;
interface
uses
System.Classes, Unit3;
type
thPrinter = class(TThread)
private
{ Private declarations }
procedure printIt;
protected
procedure Execute; override;
end;
implementation
uses
System.SysUtils;
{ thPrinter }
procedure thPrinter.Execute;
begin
{ Place thread code here }
Synchronize(printIt);
end;
procedure thPrinter.printIt;
begin
Form3.Memo1.Lines.Add(IntToStr(Form3.counter));
end;
end.
我在简单的项目上工作。但我卡住了。
我有2个帖子,它们是thCounter和thPrint。 我的计数器,将柜台增加到10亿。我想在计数器50时调用另一个线程(thPrint)并像100,150,200那样倍增以在TMemo中打印屏幕....
如何从thCounter向thPrint发送消息?
答案 0 :(得分:3)
要发信号通知另一个线程,请使用同步原语,如TSimpleEvent。
让它由thCounter
线程拥有,并在创建thPrinter
时传递对它的引用。
在thPrinter.Execute
:
while not Terminated do
begin
if waitEvent.WaitFor(100) = wrSignaled then // Keep it listening to the Terminated flag
begin
Synchronize(PrintIt);
end;
end;
在thCounter
:
waitEvent.SetEvent; // Triggers the printIt
只需创建waitEvent,以便在触发事件后自动重置。
waitEvent := TSimpleEvent.Create(nil, false,false,'');