資源描述:
《java多線程—socket編程實(shí)例》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在工程資料-天天文庫。
1、多線程JavaSocket編程示例這篇做為學(xué)習(xí)孫衛(wèi)琴<>的學(xué)習(xí)筆記吧.其中采用Java5的ExecutorService來進(jìn)行線程池的方式實(shí)現(xiàn)多線程,模擬客戶端多用戶向同一服務(wù)器端發(fā)送請求.1.服務(wù)端package?sterning;import?java.io.BufferedReader;import?java.io.IOException;import?java.io.InputStream;import?java.io.InputStreamReader;import?java.io.OutputStr
2、eam;import?java.io.PrintWriter;import?java.net.*;import?java.util.concurrent.*;public?class?MultiThreadServer?{????private?int?port=8821;????private?ServerSocket?serverSocket;????private?ExecutorService?executorService;//線程池????private?final?int?POOL_SIZE=10;//單個(gè)CPU線程池大
3、小????????public?MultiThreadServer()?throws?IOException{????????serverSocket=new?ServerSocket(port);????????//Runtime的availableProcessor()方法返回當(dāng)前系統(tǒng)的CPU數(shù)目.????????executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);????????Sys
4、tem.out.println("服務(wù)器啟動(dòng)");????}otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelon
5、gMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand????????public?void?service(){????????while(true){????????????Socket
6、?socket=null;????????????try?{????????????????//接收客戶連接,只要客戶進(jìn)行了連接,就會(huì)觸發(fā)accept();從而建立連接????????????????socket=serverSocket.accept();????????????????executorService.execute(new?Handler(socket));????????????????????????????}?catch?(Exception?e)?{????????????????e.printStackT
7、race();????????????}????????}????}????????public?static?void?main(String[]?args)?throws?IOException?{????????new?MultiThreadServer().service();????}}class?Handler?implements?Runnable{????private?Socket?socket;????public?Handler(Socket?socket){????????this.socket=socket;
8、????}????private?PrintWriter?getWriter(Socket?socket)?throws?IOException{????????OutputStream?socketOut=socket