unit Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;type
   mythread=class(Tthread)
   procedure execute;override;
   end;
  TForm1 = class(TForm)
    Button1: TButton;
    ListBox1: TListBox;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public     procedure threaddone(sender:Tobject);
    { Public declarations }
  end;var
  Form1: TForm1;
  Num:array[0..99] of integer;
  pu:integer=0;
  cs:TRTLCriticalsection;
  flages:integer=0;
  function nextnumber:integer;
implementation
procedure Tform1.threaddone(sender:Tobject);
var
i:integer;
begin
  inc(flages);
  if flages=2 then
  begin
    for i:=0 to 99 do
      begin
       listbox1.Items.Add(inttostr(num[i]));
      end;
    deletecriticalsection(cs);
  end;
end;
function nextnumber:integer;
begin
inc(pu); result:=pu;
end;
procedure mythread.execute;
var i:integer;
begin
  onterminate:=form1.threaddone;
  entercriticalsection(cs);
   for i:=0 to 49 do
   begin
   num[pu]:=nextnumber; //这行好像有问题,动行到删除临界区那行就停止了.弹出异常窗口.
        //但改为num[pu]:=pu;inc(pu);就可以了.怎么回事?请高手指教
   end;
  leavecriticalsection(cs);
end;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
    initializecriticalsection(cs);
    mythread.Create(false);
    mythread.Create(false);
end;end.

解决方案 »

  1.   

    function nextnumber:integer;
    begin
    inc(pu); result:=pu;
    end;
    这个方法不属于线程方法所以这样了,你写到线程的private里边调用一下看看如何?
      

  2.   

    如果是属于form1,就得Synchronize(NextBumber);调用了,你看看dephi5开发人员指南
      

  3.   

    我的函数定义是在interface部分的.pu也是一样的.
      

  4.   

    我试了,把方法放到了线程里面.可还是一样的错误结果.
    我明白.如果线程要与可视化组相关联,必须要用到synchronize方法.
    再帮我想想是什么原因吗?