1. 程式人生 > >delphi 中使用WaitForMultipleObjects等待執行緒執行,再執行後續程式碼

delphi 中使用WaitForMultipleObjects等待執行緒執行,再執行後續程式碼

unit1

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    btn1: TButton;
    mmo1: TMemo;
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

    procedure ThreadTest;stdcall;
implementation

uses Unit2;

{$R *.dfm}


procedure ThreadTest;stdcall;
var
    Handles:TWOHandleArray;
    //Handle:THandle;
    Test:TTestThread;
    i:Integer;
begin
    for i := 0 to 10 do
    begin
        Test := TTestThread.Create(False);
        Handles[i] := Test.Handle;
    end;
    WaitForMultipleObjects( 11, @Handles, True, INFINITE );
    Form1.mmo1.Lines.Add( '123' );
end;


procedure TForm1.btn1Click(Sender: TObject);
var
    ID:Cardinal;
begin
    CreateThread( nil, 0, @ThreadTest, nil, 0, ID );
end;



end.

unit2

unit Unit2;

interface

uses
  Classes;

type
  TTestThread = class(TThread)
  private
    { Private declarations }
  protected
    procedure Execute; override;
  end;

implementation

uses Unit1;


procedure TTestThread.Execute;
begin
  { Place thread code here }
  { Place thread code here }
  //FreeOnTerminate := False;
  form1.mmo1.Lines.Add( 'ok' );

end;

end.


程式執行效果:

ok
ok
ok
ok
ok
ok
ok
ok
ok
ok
ok
123
介面上先打印出11個執行緒輸出的“OK”,再輸出123.