简单多线程服务器实现

2014-11-24 02:45:56 · 作者: · 浏览: 2

  闲来没事,本来是在学习nio框架的,突然发现对最原始的多线程服务器都不是很了解,遂自己写了个简单的例子。


  1 package testmutithreadserver.old;
  2
  3 import java.io.IOException;
  4 import java.net.ServerSocket;
  5 import java.net.Socket;
  6
  7 import testmutithreadserver.old.threadpool.ThreadPool;
  8
  9 /**
  10 * 简单阻塞式多线程服务器(线程池处理)
  11 *
  12 * @author zhangjun
  13 *
  14 */
  15 public class Server {
  16
  17 private int port;
  18
  19 private ServerSocket serverSocket;
  20
  21 private ThreadPool threadPool;
  22
  23 private PortListenThread listener;
  24
  25 public Server(int port) {
  26 this.port = port;
  27 threadPool = new ThreadPool();
  28 }
  29
  30 public void start() {
  31 try {
  32 serverSocket = new ServerSocket(port);
  33 listener = new PortListenThread();
  34 listener.start();
  35 } catch (IOException e) {
  36 e.printStackTrace();
  37 }
  38 }
  39
  40 public void shutdown() {
  41 threadPool.shutdown();

  42 listener.finish();
  43 }
  44
  45 private class PortListenThread extends Thread {
  46
  47 private Boolean finish = false;
  48
  49 @Override
  50 public void run() {
  51 while (!finish) {
  52 try {
  53 final Socket socket = serverSocket.accept();
  54 threadPool.execute(new Runnable() {
  55
  56 @Override
  57 public void run() {
  58 new TestMessage(socket).execute();
  59 }
  60 });
  61 } catch (IOException e) {
  62 e.printStackTrace();
  63 }
  64
  65 }
  66 }
  67
  68 public void finish() {
  69 finish = true;
  70 }
  71
  72 }
  73
  74 public static void main(String[] args) {
  75 int port = 8888;
  76 System.out.println("server is listening on port: " + port);
  77 new Server(port).start();
  78 }
  79
  80 }
  81