unit UTimeDisplay;interfaceuses
  Classes, Graphics, ExtCtrls,Controls,SysUtils,Dialogs,StdCtrls;type
  TCurrTimeDisplay= Class(TThread)
  Private
    aTimer:TTimer;
    aLabel:TLabel;
  protected
    procedure Execute; override;
    procedure DoTerminate;override;
  Public
    Constructor Create(var TmShowLbl:TLabel);
    procedure TimerTimer(Sender:TObject);
  end;implementationConstructor TCurrTimeDisplay.Create(Var TmShowLbl:TLabel);
begin
  //Priority:=tpHigher;
  FreeOnTerminate:=True;
  aLabel:=TmShowLbl;
  aTimer:=TTimer.Create(nil);
  with aTimer do
  begin
    Interval:=1000;
    OnTimer:=TimerTimer;
  end;
  inherited Create(False);
end;Procedure TCurrTimeDisplay.Execute;
begin
  TimerTimer(aTimer);
end;procedure TCurrTimeDisplay.TimerTimer(Sender:TObject);
begin
  aLabel.Caption:=TimeToStr(Time);
  aLabel.Refresh;
  aTimer.Enabled:=True;
end;Procedure TCurrTimeDisplay.DoTerminate;
begin
  if aTimer<>nil then
    aTimer.Free;
end;现在问题是使用这个线层的程序 只要lose focus(鼠标点到程序外面)就出现“read voliation 0×00000...”错误怎么控制线程的结束 我不会。同时还有个问题,我这样写主线层上的赋给“Var TmShowLbl:TLabel”的label 并不会一秒一秒变化 而是就第一次执行的时间 :(

解决方案 »

  1.   

    你这个程序问题比较多。
    大的有:
    1、
    Procedure TCurrTimeDisplay.Execute;
    begin
      TimerTimer(aTimer); //此句执行完毕后,线程就要销毁了,也就是执行DoTerminate,所以“label 并不会一秒一秒变化 而是就第一次执行的时间”
    end;
    2、TCurrTimeDisplay.TimerTimer中对共享资源aLabel直接操作,这是不安全的,应该放在TThread.Synchronize中。
    其他有:
    1、Constructor Create(var TmShowLbl:TLabel);中没必要引用传递TmShowLbl,因为TLabel本身就是指针,宜改为:
    Constructor Create(TmShowLbl:TLabel);
    2、TCurrTimeDisplay.DoTerminate;中应该集成父类的方法。“怎么控制线程的结束 我不会”,你这个线程根本就不好控制什么时候结束,原因是根本就不应该在线程中使用TTimer。线程结束是在Execute中控制的,如果你一定要采用现在的设计方式,那么应该加一个控制变量,在Execute中判断该变量的值从而控制Timer.Enabled。—————————————————————————————————
    宠辱不惊,看庭前花开花落,去留无意;毁誉由人,望天上云卷云舒,聚散任风。
    —————————————————————————————————
      

  2.   

    你没有使用Synchronize对VCL进行同步访问啊,的确问题比较多
      

  3.   

    看你的这个程序好象就是要一个显示时间的label,就向要一个表一样,完全没有必要用多线程啊,只用timer就可以办到了
      

  4.   

    timer本身就是一个线程,没必要这样做。