Skip to content

delphi使用多线程时,界面死锁

在使用线程时,发现,如果同时打开多个线程,并且每个线程都在等待的话,那么,界面就会死锁,无法操作。而cpu占用率会达到100%。解决办法是在线程中加上sleep即可。

以下为例子:

?View Code DELPHI
unit Unit1;
 
interface
 
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;
 
type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
var
  Form1: TForm1;
 
implementation
 
uses
  Unit2;
 
{$R *.dfm}
 
procedure TForm1.Button1Click(Sender: TObject);
var
  i: integer;
  panel: TPanel;
begin
  for i := 0 to 8 do
  begin
    panel := TPanel.Create(Self);
    panel.Parent := Self;
    panel.Top := i * 20;
    panel.Left := i * 50;
    panel.Width := 50;
    panel.Caption := IntToStr(i);
    thread.Create(panel);
  end;
end;
 
end.
 
unit Unit2;
 
interface
 
uses
  Classes, ExtCtrls, SysUtils;
 
type
  thread = class(TThread)
  private
    { Private declarations }
    i:      integer;
    Fpanel: TPanel;
  protected
    procedure Execute; override;
    procedure update;
  public
    constructor Create(Panel: TPanel);
  end;
 
implementation
 
{ thread }
procedure thread.update;
begin
  Fpanel.Caption := IntToStr(i);
  FPanel.Refresh;
end;
 
procedure thread.Execute;
begin
  { Place thread code here }
  i := 0;
  while not Terminated do
  begin
    //如无sleep,则当线程超过1个的话,界面就会死锁。
    Sleep(1);
    //也可不用synchronize,但关闭时,要处理线程。
    Synchronize(update);
    // update;
    Inc(i);
  end;
end;
 
constructor thread.Create(Panel: TPanel);
begin
  FreeOnTerminate := True;
  Fpanel := Panel;
  inherited Create(False);
end;
 
end.
标签:

相关日志

Post a Comment

Your email is never published nor shared. Required fields are marked *