在主程序中做一段循环,在这之前建一个子线程对一个数进行累加,
现发现在主程序循环的时候子线程不进行累加
如何处理在主程序循环的时候子线程也进行累加

解决方案 »

  1.   

    对,有没有进去非常重要!其次就是,主程序建立线程的时候  线程类.Create(False); 你是否用的是True
    如果是用True的话,建立这个线程的时候,不会执行的,除非你在发出开始执行的指令。
      

  2.   

    先谢谢大家了,我把源码贴上来
    unit Unit1;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls, ComCtrls;type
      TSplash = class(TThread)
    protected
         procedure SetProgress;
         procedure Execute; override;
      end;
      TForm1 = class(TForm)
        ProgressBar1: TProgressBar;
        Button1: TButton;
        Button2: TButton;
        Edit1: TEdit;
        Edit2: TEdit;
        Edit3: TEdit;
        procedure Button1Click(Sender: TObject);
        procedure Button2Click(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
    aSplash :TSplash;
      end;var
      Form1: TForm1;implementation{$R *.dfm}{ TSplash }procedure TSplash.Execute;
    var
    iBegin:Integer;
    begin
      inherited;
    FreeOnTerminate:=true;
        while true do
        begin
         iBegin := GetTicKCount;
         while GetTickCount-iBegin <500 do
            begin
             ;
            end;
        Synchronize(SetProgress);
        end;
    end;procedure TSplash.SetProgress;
    begin
        Form1.ProgressBar1.StepBy(8);
        if Form1.ProgressBar1.Position > 95 then
            Form1.ProgressBar1.Position := 20;
    end;procedure TForm1.Button1Click(Sender: TObject);
    var
    iBegin :Integer;
    begin
    iBegin := GetTicKCount;
    while (GetTickCount-iBegin<4000) do
        begin
         ;
        end;
    end;procedure TForm1.Button2Click(Sender: TObject);
    begin
    aSplash := TSplash.Create(false);
    end;end.
    ------------------------------
    程序运行后按Button2,这时ProgressBar1是会响应一直动的,但按了
    Button1后,ProgressBar1就不动了,直到Button1完成后ProgressBar1才
    继续响应;现希望不改动Button1的代码,在Button1里的代码运行时
    ProgressBar1也在响应
      

  3.   

    因为 Synchronize 所执行的方法,要在主线程中执行,所以 Synchronize 等待主线程进入消息循环,然后执行所传递的方法。
    如果你的主线程没有空闲,则无法执行你的方法
      

  4.   

    可以这样:
    procedure TForm1.Button1Click(Sender: TObject);
    var
    iBegin :Integer;
    begin
    iBegin := GetTicKCount;
    while (GetTickCount-iBegin<4000) do
        begin
         Application.ProcessMessages;//可以处理子线程中的同步函数
        end;
    end;
      

  5.   

    Button1里的代码是不能修改的,本来是调用一个远程的过程,相当于在做空循环,我这里是模拟调用的,因此要求Button1里代码不修改而能实现
      

  6.   

    象这种情况,那么我认为你可以不用 Synchronize 调用,因为在这个过程中,可以保证线程是安全的。试试