JIAMS的比喻是比较形象的。
真正的冯.诺依曼体系的计算机结构中,CPU在一个时刻只能对单一任务进行处理。但在WIN95及以上版本的OS时常用到多任务分时处理。
多线程把单一的进程划分为多个不同的部分,每个部分被称为线程,每个线程都由CPU分时处理。
我提供个书上的例子作为参考:(你比较一下线程和非线程情况就会有感性认识了)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ToolWin, ComCtrls;
const
ccolcount=20;
crowcount=20;
cheight=20;
cwidth=25;
type
TForm1 = class(TForm)
ToolBar1: TToolBar;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
procedure Button4Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
function threaddraw(p
ointer):longint;stdcall;
function threadcount(p
ointer):longint;stdcall;
procedure pointswap(var npointa,npointb:tpoint);
implementation
{$R *.DFM}
procedure pointswap(var npointa,npointb:tpoint);
var
temp:tpoint;
begin
temp.x:=npointa.x;
temp.y:=npointa.y;
npointa.x:=npointb.x;
npointa.y:=npointb.y;
npointb.x:=temp.x;
npointb.y:=temp.y;
end;
function threaddraw(p
ointer):longint;stdcall;
var
a:array [1..ccolcount*crowcount] of tpoint;
i,j,k:integer;
begin
k:=0;
for i:=1 to ccolcountdo
for j:=1 to crowcountdo
begin
inc(k);
a[k].x:=i;
a[k].y:=j;
end;
for i:=1 to ccolcount*crowcountdo
pointswap(a
,a[succ(random(ccolcount*crowcount))]);
form1.canvas.brush.color:=form1.color;
form1.canvas.fillrect(rect(0,0,ccolcount*cwidth,crowcount*cheight));
for i:=1 to ccolcount*crowcountdo
begin
form1.canvas.brush.color:=random($FFFFFF);
j:=pred(a.x)*cwidth;
k:=pred(a.y)*cheight;
sleep(20);
form1.canvas.fillrect(rect(j,k,j+cwidth,k+cheight));
end;
end;
function threadcount(pointer):longint;stdcall;
var
i:integer;
dc:hdc;
s:string;
begin
dc:=getdc(form1.handle);
for i:=0 to 1000000do
begin
s:=inttostr(i);
textout(dc,200,200,PCHAR(S),Length(s));
end;
releasedc(form1.handle,dc);
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
threaddraw(nil);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
hthread:thandle;
threadid:dword;
begin
hthread:=createthread(nil,0,@threadcount,nil,0,threadid);
if hthread=0 then
messagebox(handle,'线程建立失败!',nil,MB_OK);
end;
procedure TForm1.Button3Click(Sender: TObject);
var
hthread:thandle;
threadid:dword;
begin
hthread:=createthread(nil,0,@threaddraw,nil,0,threadid);
if hthread=0 then
messagebox(handle,'线程建立失败!',nil,MB_OK);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
threadcount(nil);
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
close;
end;
end.