您的位置:首页 > 其它

最简单的线程并发例子

2006-11-06 11:31 204 查看
用一个线程来实现这个功能1:变量i从0--40000来循环改变一个label1的值,值和i的值一样

然后不用线程也实现这个label2的显示功能2

如何把功能1和功能2同时进行?

1、建立主程序
2、创建线程对象(FILE->NEW->Thread Object)
3、编写线程代码
(编写同步方法成员)
4、在主程序中建立线程对象(Create方法)
5、主程序中调用线程

下面的是主程序
unit Unit1;

interface

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

type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation

uses Unit2;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
i:integer;
TestThread:CTestThread;
begin
TestThread:=CTestThread.Create(False);
for i:=1 to 40000 do
begin
Label1.Caption:=IntToStr(i);
end;
TestThread.Terminate;
end;

end.

以下是线程单元代码,Excute是线程单元的入口函数
unit Unit2;

interface

uses
SysUtils,Classes,Unit1;

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

implementation

procedure CTestThread.Execute;
begin
{ Place thread code here }
{ Place thread code here }
while not Terminated do
begin
Synchronize(Test); //同步化机制..
end;
end;

procedure CTestThread.Test;
var
i:integer;
begin
for i:=1 to 40000 do
Form1.Label2.Caption:=IntToStr(i);
end;
end.

1、我知道TMsgThread.Create(True)这样可以创建一个线程,如果参数为true,线程创建但不执行。
否则,如果是false,创建并且执行线程。
2、FreeOnTerminate:=true;线程执行完毕以后就自动释放了
3、线程创建很消耗资源。所以如果定时要执行线程的代码,就不要把它释放。

基于以上的考虑,我对下面的代码是这样使用的。

{线程类定义}
TMsgThread = class(TThread)
private
{ Private declarations }
procedure ShowInMemo;
protected
procedure Execute; override;
public

end;

procedure TWeather.Execute;
begin
{ Place thread code here }
FreeOnTerminate:=false;//不释放
Synchronize(ShowInMemo);
end;

{主程序}
var
newThrd:TMsgThread;

procedure TForm1.Button1Click(Sender: TObject);
begin
newThrd:=TMsgThread.Create(True);
with newThrd do
begin
Resume;
end;

end;

procedure TForm1.FormDestroy(Sender: TObject);
begin

newThrd.free; //主窗体关闭的时候释放线程对象
end;

线程同步问题

1、哪些东西要用同步Synchronize? 我知道可视化组件不支持是都不支持吗?

2、我的项目是收到数据用线程1处理保存,如果电脑快速收数据,我的的线程1基本上都用到可视化组件(adoquery/spcomm)也就是都要用Synchronize保护吧?

3、如果我想提高速度是不是用多套组件好一些,比如adoquery1、2、3 当收到数据加上一个序号地,运行线程时如果mod3=0、1、2就用不同的adoquery?

和界面GUI有关的时候用Synchronize.

ADOQuery并不是可视控件,所以也用不到。

线程在执行一个长时间的操作/循环时使用,如果是收数据的速度很快,保存数据的速度相对慢的话,最主要的不是用几个ADOQuery而是如何将这发来的数据快速接收。你的串口一秒能来多少数据呀!

要不还是开一个缓冲区,将串口来的数据全部先保存到缓冲区中,然后开一个线程,线程时创建一个ADOQuery将缓冲区数据保存。这样你的数据来的在快也没有关系了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: