First, using the callable interface
PublicClassDatepoolserver {PublicStaticvoid Main (string[] args) {Executorservice pool = Executors.newfixedthreadpool ();//Create a 50-size thread pool Try (serversocketServer =New ServerSocket (7456)) {while (true) {Socket connection =Server.accept ();callable<void> task =new Datetask (connection); Void is java.lang.void Pool.submit (Task);//Submit task to thread pool, wait for call} }catch (IOException e) {e.printstacktrace ();}}Public ClassDatetaskImplements callable<void>{private Socket Connection;Public Datetask (Socket connection) {This.connection = connection; } @OverridePublic VoidPager() {The call to this method is called in this taskVoid is java.lang.void
Long threadId = Thread. CurrentThread (). GetId ();
String name =thread. CurrentThread (). GetName ();
System. err.println ("The current thread's id" +threadid+"the name of the current thread" +name);
Writer writer;try {writer =New OutputStreamWriter (Connection.getoutputstream ()); Date now =New Date (); Writer.write (now.tostring () +catch (IOException e) {e.printstacktrace ();} finally {try {if (connection! =) Span class= "Hljs-keyword" >null) connection.close (); } catch (IOException e) {e.printstacktrace ();}} return null; }}}
Second, use runnable interface
Server:
private serversocket serversocket = null;
private Socket socket = null;
ServerSocket = New ServerSocket (port);
Socket socket = null;
Executorservice Fixedthreadpool = executors.Newfixedthreadpool (3);
while (true) {
Socket =serversocket.accept ();
runnable thread = new threadedserver (socket) Fixedthreadpool.submit (thread)
}
Service Thread class:
public class Threadedserver implements Runnable {
Private socket socket = null;
private static outputstream out = null; //DECLARE output stream
private InputStream in = null; //Declare input stream
< Span style= "COLOR: #cc7832" > &NBSP;
PublicThreadedserver (Socket s)Throws Exception {
Socket = S;
try {
out =Socket.getoutputstream ();Returns the output stream for this socket
in =Socket.getinputstream (); //returns the input stream for this socket
} catch ( Exception e) {
E.printstacktrace () ;
socket.shutdowninput () ;
socket.shutdownoutput () ;
socket.close () ;
log.info ( "Abnormal close Socket----->" + socket) }
} /span>
public void Run () {
long threadId = Thread.currentthread (). GetId () String name =thread. currentthread (). GetName () ;
System. err.println ( "ID of current thread" +threadid+< Span style= "COLOR: #6a8759" > "name of the current thread" +name)
}
}
Sockect Programming Thread Pool