程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> 多線程編程(3)-從CreateThread說起[續](2)

多線程編程(3)-從CreateThread說起[續](2)

編輯:Delphi

代碼文件:unit Unit1;
interface
uses
 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 Dialogs, StdCtrls, ExtCtrls;
type
 TForm1 = class(TForm)
  Button1: TButton;
  Button2: TButton;
  Button3: TButton;
  Timer1: TTimer;
  procedure Button1Click(Sender: TObject);
  procedure Button2Click(Sender: TObject);
  procedure Button3Click(Sender: TObject);
  procedure FormCreate(Sender: TObject);
  procedure Timer1Timer(Sender: TObject);
 end;
var
 Form1: TForm1;
implementation
{$R *.dfm}
var
 hThread: THandle; {線程句柄}
 num: Integer;   {全局變量, 用於記錄隨機數}
{線程入口函數}
function MyThreadFun(p: Pointer): Integer; stdcall;
begin
 while True do {假如線程不掛起, 這個循環將一直循環下去}
 begin
  num := Random(100);
 end;
 Result := 0;
end;
{建立並掛起線程}
procedure TForm1.Button1Click(Sender: TObject);
var
 ID: DWord;
begin
 hThread := CreateThread(nil, 0, @MyThreadFun, nil, CREATE_SUSPENDED, ID);
 Button1.Enabled := False;
end;
{喚醒並繼續線程}
procedure TForm1.Button2Click(Sender: TObject);
begin
 ResumeThread(hThread);
end;
{掛起線程}
procedure TForm1.Button3Click(Sender: TObject);
begin
 SuspendThread(hThread);
end;
{下面是窗體代碼}
procedure TForm1.FormCreate(Sender: TObject);
begin
 Timer1.Interval := 100;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
 Text := IntToStr(num);
end;
end.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved