Simple demo of thread pool

Source: Internet
Author: User

Server-side:

 Public  class Server {    Private intport=8821;PrivateServerSocket ServerSocket;PrivateExecutorservice Executorservice;//thread pool    Private Final intPool_size=Ten;//Single CPU thread pool size     Public Multithreadserver()throwsioexception{serversocket=NewServerSocket (port);the//runtime availableprocessor () method returns the number of CPUs for the current system.Executorservice=executors.newfixedthreadpool (Runtime.getruntime (). Availableprocessors () *POOL_SIZE); System.out.println ("Server started! "); } Public void Service(){ while(true) {Socket socket=NULL;Try{//Receive customer connection, as long as the customer is connected, will trigger accept (); Establish a connection! Socket=serversocket.accept (); Executorservice.execute (NewServerconthread (socket)); }Catch(Exception e)              {E.printstacktrace (); }          }      } Public Static void Main(string[] args)throwsIOException {NewServer (). Service (); }  }

Thread:

 Public  class serverconthread implements Runnable{      PrivatePrintWriter PW =NULL;PrivateBufferedReader br=NULL;PrivateSocket socket; PublicServerconthread (socket socket) {this.socket=socket; }PrivatePrintWriter getwriter (socket socket) throws ioexception{OutputStream Socketout=socket.getoutputstream ();return NewPrintWriter (Socketout,true); }PrivateBufferedReader Getreader (socket socket) throws ioexception{InputStream Socketin=socket.getinputstream ();return NewBufferedReader (NewInputStreamReader (Socketin)); } Publicvoid Run () {Try{System.out.println ("New Connection:"+socket.getinetaddress () +":"+socket.getport ());              Br=getreader (socket);              Pw=getwriter (socket); String msg=NULL; while((Msg=br.readline ())! =NULL) {System.out.println ("The client said:"msg); Pw.println ("I am the server!" ");        } br.close (); }Catch(IOException e)            {E.printstacktrace (); System.out.println ("Input output stream exception!" "); }Catch(Exceptione) {e.printstacktrace (); }finally{Try{if(socket!=NULL) Socket.close (); }Catch(IOException e)                  {E.printstacktrace (); System.out.println ("Input output stream exception!"            ); }          }      }  }

Client:

 Public classClient { Public Static void Main(string[] args) {intNumtasks =Ten; Executorservice exec = Executors.newcachedthreadpool (); for(intI=0;i<Ten; i++) {Exec.execute (CreateTask (i)); }    }//Define a simple task    Private StaticRunnableCreateTask(FinalintTaskID) {return NewRunnable () {PrivateSocket socket =NULL;Private intport=6666; Public void Run() {System. out. println ("Task"+ TaskID +": Start");Try{socket =NewSocket ("localhost", port);                    OutputStream socketout = Socket.getoutputstream (); PrintWriter PW =NewPrintWriter (socketout); Pw.println ("I am the client!" "); Pw.flush ();//Receive server feedbackBufferedReader br =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); String msg =NULL; while(msg = Br.readline ())! =NULL) System. out. println (msg); }Catch(IOException e)                  {E.printstacktrace ();      }              }          }; }  }

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Simple demo of thread pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.