在delphi中用如下方式建一线程(因在delphi8中好象只能这么建)
Procedure Tform1.Button1_Click(sender: System.Object; e: System.EventArgs);
var
t1:Thread;
begin
t1:=Thread.Create(Threadstart(MyThreadProc));
end;procedure MyThreadProc();
begin
//这里要处理一个全局的变量,该全局变量应定义在哪里?
//不能定义在public或private,因为该procedure不是该form上的
end;
若是线程类专用的全局,可以定义在线程类实现的单元的实现部分,且用threadvar定义,如s,这样是线程安全的。
unit Unit1;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;var
Form1: TForm1;implementation
var
Gobalvar:integer;{$R *.dfm}end.
unit Unit2;interfaceuses
Classes;type
TThread1 = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;implementation
threadvar
S: AnsiString;
{ 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 TThread1.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }{ TThread1 }procedure TThread1.Execute;
begin
{ Place thread code here }
end;end.
Windows;
type
TtestFM = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end; IntPutThread=class(TThread)
private
AutoString:string;
protected
procedure Execute;override;
public
constructor Create(str:string);
end;
implementationconstructor IntPutThread.Create(str:string);
begin
AutoString:=str;
inherited Create(false);
end;procedure IntPutThread.Execute;
begin
......
end;