//第一種:傳指標
tparam=record
trdid:integer;
sckt:tsocket;
end;
varparam:^tparam;
new(param);
param^.trdid:=threadcount;
param^.sckt:=s;
hthread:=createthread(nil,0,@childthrd,param,0,threadid); //建立childthrd子執行緒
if hthread=0 then
begin
writeln('createthread() fail');
endelse
begin
inc(threadcount);
//子執行緒:
function childthrd(p:pointer):longint;stdcall;
varpklen:integer;
threadid:integer;
asocket:tsocket;
temp:tstringlist;
buf:array[0..1024] of char;
sendstr,cmd:string;
handle,ichandle,clinichandle:integer;
m:double;
bsend:boolean;
begin
trywhile true do
begin
bsend:=true;
result:=0;
threadid:=tparam(p^).trdid;
asocket:=tparam(p^).sckt;
pklen:=0;
fillchar(buf,sizeof(buf),0);
pklen:=recv(asocket,buf,sizeof(buf),0); //接收資料
cmd :=strpas(buf);
//第二種格式:傳位址
s,ns:tsocket;//type:u_int|integer;
pktlen:integer;
server:tsockaddr;//tpye:sockaddr_in
client:psockaddr;//type:^sockaddr_in
namelen:pinteger;//type:^integer;
threadid:dword;
createthread(nil,0,@socketworkthread,pointer(ns),0,threadid);
procedure socketworkthread(ns:tsocket); stdcall; //stdcall 是必須的,否則接收不到引數
varrecvbuf,sendbuf:array[0..1025] of char;
begin
trywhile true do
begin
pktlen:= recv(ns,recvbuf,1024,0); //接收資料
if pktlen<1 then //如果返回值小於1說明連線被斷開或者錯誤
begin
writeln(id:+inttohex(ns,2)+ exit.);
exit;
end;
strcopy(sendbuf,#13#10welcome.#13#10);
send(ns,sendbuf,strlen(sendbuf),0); //傳送回應
end;
except
writeln(socketworkthread error.);
exit;
end;
end;
執行緒建立的兩種方式
建立執行緒的兩種方式 1.繼承thread並重寫方法,在run方法中定義執行緒要執行的任務 class mythread extends thread public class threaddemo1 2.實現runable介面並重寫run方法 class myrunnable implements...
建立執行緒的兩種方式
thread thread new thread catch interruptedexception e system.out.println thread.currentthread getname system.out.println this.getname thread.start thr...
建立執行緒的兩種方式
一 繼承thread類 public class mythead extends thead override public void run public class demo01 二 實現runnable介面 public class myrunnable implements runnable...