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

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

以下为例子:

unit Unit1;
  1.  
  2. interface
  3.  
  4. uses
  5.   Windows , Messages , SysUtils , Variants , Classes , Graphics , Controls , Forms ,
  6.   Dialogs , StdCtrls , ExtCtrls ;
  7.  
  8. type
  9.   TForm1 = class (TForm )
  10.     Button1 : TButton ;
  11.     procedure Button1Click (Sender : TObject ) ;
  12.   private
  13.     { Private declarations }
  14.   public
  15.     { Public declarations }
  16.   end ;
  17.  
  18. var
  19.   Form1 : TForm1 ;
  20.  
  21. implementation
  22.  
  23. uses
  24.   Unit2 ;
  25.  
  26. {$R *.dfm}
  27.  
  28. procedure TForm1 . Button1Click (Sender : TObject ) ;
  29. var
  30.   i : integer ;
  31.   panel : TPanel ;
  32. begin
  33.   for i : = 0 to 8 do
  34.   begin
  35.     panel : = TPanel . Create ( Self ) ;
  36.     panel . Parent : = Self ;
  37.     panel . Top : = i * 20 ;
  38.     panel . Left : = i * 50 ;
  39.     panel . Width : = 50 ;
  40.     panel . Caption : = IntToStr (i ) ;
  41.     thread . Create (panel ) ;
  42.   end ;
  43. end ;
  44.  
  45. end .
  46.  
  47. unit Unit2 ;
  48.  
  49. interface
  50.  
  51. uses
  52.   Classes , ExtCtrls , SysUtils ;
  53.  
  54. type
  55.   thread = class (TThread )
  56.   private
  57.     { Private declarations }
  58.     i :       integer ;
  59.     Fpanel : TPanel ;
  60.   protected
  61.     procedure Execute ; override ;
  62.     procedure update ;
  63.   public
  64.     constructor Create (Panel : TPanel ) ;
  65.   end ;
  66.  
  67. implementation
  68.  
  69. { thread }
  70. procedure thread . update ;
  71. begin
  72.   Fpanel . Caption : = IntToStr (i ) ;
  73.   FPanel . Refresh ;
  74. end ;
  75.  
  76. procedure thread . Execute ;
  77. begin
  78.   { Place thread code here }
  79.   i : = 0 ;
  80.   while not Terminated do
  81.   begin
  82.     //如无sleep,则当线程超过1个的话,界面就会死锁。
  83.     Sleep ( 1 ) ;
  84.     //也可不用synchronize,但关闭时,要处理线程。
  85.     Synchronize (update ) ;
  86.     // update;
  87.     Inc (i ) ;
  88.   end ;
  89. end ;
  90.  
  91. constructor thread . Create (Panel : TPanel ) ;
  92. begin
  93.   FreeOnTerminate : = True ;
  94.   Fpanel : = Panel ;
  95.   inherited Create ( False ) ;
  96. end ;
  97.  
  98. end .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值