一个例子,多线程排序:一.基本的方法如下: 1.从Tthread类派生一个新类。(创建TSortThread类)
2.定义新类的Create方法。
3.定义新类的Execute方法,并在Execute方法中插入线程运行时执行的代码。
4.引用类方法创建实例。
二.例子的详细代码及说明:
首先,新建一个单元,保存为mysort.pas.在此单元中,我们创建了一个TSortThread类,它从TThread类中继承而来,所以当我们在程序中创建这个类的一个实例时,也就是创建了一个新的线程。
接着,在该类中定义一个Sort方法,用来对数组进行排序,同时TSortThread类超越了TThread类的构造方法Create和Execute,在execute方法中,调用了对数组进行排序的Sort方法。具体代码如下: unitmysort;
interface
usesClasses;//TThread类在Classes中被定义。
type
PSortArray=TSortArray;
TSortArray=array.[0..MaxIntdivSize
Of(Integer)-1]ofInteger;
{此处定义了TsortThread类}
TSortThread=class(TThread)
Private
{在TSortThread类中定义了如下几个私有变元}
FSortArray:PSortArray;
FSize:Integer;
FA,FB,FI,FJ:Integer;
Protected
{类TSortThread超越了类Tthread的Execute方法}
procedure Execute;override;
{类TsortThread添加了一个Sort方法}
procedure Sort(varA:arrayofInteger); public
{类TSortThread超越了类Tthread的构造方法}
constructorCreate(varSortArray:arrayofInteger);
end;
implementation
constructorTSortThread.Create(varSortArray:arrayofInteger);
begin
FSortArray:=@SortArray;
FSize:=High(SortArray)-Low(SortArray)+1;
FreeOn Terminate:=True;
inheritedCreate(False);
end;
{当线程开始时,Execute方法将被调用。}
procedure TSortThread.Execu
te;
begin
Sort(Slice(FSortArray,FSize));
end;
{下面实现了冒泡法排序}
procedure TSortThread.Sort(varA:arrayofInteger); var
I,J,T:Integer;
begin
for I:=High(A)downto Low(A) do
for J:=Low(A)to High(A)-1 do
if A[J]>A[J+1] then
begin
T:=A[J];
A[J]:=A[J+1];
A[J+1]:=T;
if Terminated then Exit;
end;
end;
end
2.定义新类的Create方法。
3.定义新类的Execute方法,并在Execute方法中插入线程运行时执行的代码。
4.引用类方法创建实例。
二.例子的详细代码及说明:
首先,新建一个单元,保存为mysort.pas.在此单元中,我们创建了一个TSortThread类,它从TThread类中继承而来,所以当我们在程序中创建这个类的一个实例时,也就是创建了一个新的线程。
接着,在该类中定义一个Sort方法,用来对数组进行排序,同时TSortThread类超越了TThread类的构造方法Create和Execute,在execute方法中,调用了对数组进行排序的Sort方法。具体代码如下: unitmysort;
interface
usesClasses;//TThread类在Classes中被定义。
type
PSortArray=TSortArray;
TSortArray=array.[0..MaxIntdivSize
Of(Integer)-1]ofInteger;
{此处定义了TsortThread类}
TSortThread=class(TThread)
Private
{在TSortThread类中定义了如下几个私有变元}
FSortArray:PSortArray;
FSize:Integer;
FA,FB,FI,FJ:Integer;
Protected
{类TSortThread超越了类Tthread的Execute方法}
procedure Execute;override;
{类TsortThread添加了一个Sort方法}
procedure Sort(varA:arrayofInteger); public
{类TSortThread超越了类Tthread的构造方法}
constructorCreate(varSortArray:arrayofInteger);
end;
implementation
constructorTSortThread.Create(varSortArray:arrayofInteger);
begin
FSortArray:=@SortArray;
FSize:=High(SortArray)-Low(SortArray)+1;
FreeOn Terminate:=True;
inheritedCreate(False);
end;
{当线程开始时,Execute方法将被调用。}
procedure TSortThread.Execu
te;
begin
Sort(Slice(FSortArray,FSize));
end;
{下面实现了冒泡法排序}
procedure TSortThread.Sort(varA:arrayofInteger); var
I,J,T:Integer;
begin
for I:=High(A)downto Low(A) do
for J:=Low(A)to High(A)-1 do
if A[J]>A[J+1] then
begin
T:=A[J];
A[J]:=A[J+1];
A[J+1]:=T;
if Terminated then Exit;
end;
end;
end
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货