有感于<如果你用单线程写Socket>

看了<如果你用单线程写Socket>楼主写的socket例子,自己今天抽空也写了一个socket的例子,基于concurrent包的线程池的,发出来给大家看看.
package com.sluggard.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentServer {
	
	private boolean stat = true;
	
	private ExecutorService executorService = Executors.newCachedThreadPool();
	
	private ServerSocket server;
	
	public void start() {
		try {
			server = new ServerSocket(9999);
			while(stat) {
				Socket socket = server.accept();
				executorService.submit(new MyCallable(this, socket));
			}
			server.close();
			executorService.shutdown();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void stop() {
		stat = false;
	}
	
	//通过这个类提供了一个简单的退出功能
	private static class MyCallable implements Callable<Socket> {

		ConcurrentServer source;
		
		Socket socket;
		
		@Override
		public Socket call() throws Exception {
			String s;
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			while((s = br.readLine()) != null) {
				if("quit".equals(s)){
					socket.close();
					source.stop();
				}
				System.out.println(s);
			}
			return null;
		}

		private MyCallable(ConcurrentServer source, Socket socket) {
			super();
			this.source = source;
			this.socket = socket;
		}

	}

	public static void main(String[] args) {
		ConcurrentServer server = new ConcurrentServer();
		server.start();
	}

}

你可能感兴趣的:(java,多线程,.net,socket,Mina)