我以前学习线程时写的一个例子,你看看吧
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,FileCtrl;
type
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
ComboBox1: TComboBox;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
procedure ThreadDone(Sender: Tobject);
public
{ Public declarations }
end;
//¶¨ÒåÏß³Ì
TFooThread = class(TThread)
protected
procedure execute;override;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const MaxSize=128;
var
NextNumber:integer=0;
do
neFlags:integer=0;
GlobalArray:array[1..MaxSize] of integer;
//CS:TRTLCriticalSection;
hMutex:Thandle=0;
{ TFooThread }
function GetNextNumber: integer;
begin
Result:=NextNumber;
inc(nextNumber);
end;
procedure TFooThread.execute;
var
i:integer;
begin
onTerminate:=Form1.ThreadDone;
//EnterCriticalSection(CS);
if WaitForSingleObject(hMutex,INFINITE)=WAIT_OBJECT_0 then
begin
for i :=1 to MaxSize do
begin
Globalarray:=GetNextNumber;
// sleep(5);
end;
//LeaveCriticalSection(cs);
end;
ReleaseMutex(hMutex);
end;
procedure TForm1.ThreadDone(Sender: Tobject);
var
i,stop:integer;
begin
inc(doneflags);
stop:=strtoint(comboBox1.text);
ifdo
neflags=stop then
begin
listbox1.Items.Clear ;
for i := 1 to MaxSizedo
Listbox1.Items.Add(inttostr(GlobalArray));
// DeleteCriticalSection(cs);
CloseHandle(hMutex);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
hMutex:=CreateMutex(nil,false,nil);
// InitializeCriticalSection(cs);
do
neFlags:=0;
nextNumber:=0;
TFooThread.Create(False);
TFooThread.Create(False);
TFooThread.Create(False);
// showmessage(trim(datetimetostr(now)));
end;
procedure TForm1.Button2Click(Sender: TObject);
var
i:integer;
fname:string;
begin
chdir('e:/temp');
if (not directoryExists(datetostr(now))) then
mkdir(datetostr(now));//½¨Á¢ÈÕÆÚĿ¼
fname:=datetostr(now)+'_0.txt';
chdir(datetostr(now));
i:=0;
while (FileExists(fname))do
begin
i:=i+1;
fname:=datetostr(now)+'_'+IntToStr(i)+'.txt';
end;
listbox1.Items.SaveToFile(fname);
end;
end.