SingleThread,MutiThread and Thread Pool(2)

接上上编著, 现在简单说说多线程服务端程序的实现。多线程服务端与单线程最主要的不同地方在于接收请求的循环:
 ......
public void run(){
	synchronized(this){
		this.runningThread = Thread.currentThread();
	}
	openServerSocket();

	while(! isStopped()){
		Socket clientSocket = null;
		try {
		clientSocket = this.serverSocket.accept();
	} catch (IOException e) {
		if(isStopped()) {
			System.out.println("Server Stopped.") ;
			return;
		}
		throw new RuntimeException(
		"Error accepting client connection", e);
		}
		try {

		new Thread(
			new WorkerRunnable(
                		clientSocket, "Multithreaded Server")
  	        ).start();

		} catch (IOException e) {
		//log exception and go on to next request.
		}
	}

	System.out.println("Server Stopped.");
}


 ......
public class WorkerRunnable implements Runnable{

    protected Socket clientSocket = null;
    protected String serverText   = null;

    public WorkerRunnable(Socket clientSocket, String serverText) {
        this.clientSocket = clientSocket;
        this.serverText   = serverText;
    }

    public void run() {
        try {
            InputStream input  = clientSocket.getInputStream();
            OutputStream output = clientSocket.getOutputStream();
            long time = System.currentTimeMillis();
            output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " +
                    this.serverText + " - " +
                    time +
                    "").getBytes());
            output.close();
            input.close();
            System.out.println("Request processed: " + time);
        } catch (IOException e) {
            //report exception somewhere.
            e.printStackTrace();
        }
    }
}



由上代码可知,当某个处理请求时间太长时,并不会阻塞总个服务端(除非处理请求的占用全部的cpu,或者占用全部的带宽资源)。服务端可以花更少时间在serverSocket.accept()的调用上。

你可能感兴趣的:(thread,多线程,socket,Go)