知识大全 简单多线程服务器实现

Posted

篇首语:千金一刻莫空度,老大无成空自伤。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 简单多线程服务器实现相关的知识,希望对你有一定的参考价值。

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

   package testmutithreadserver old;

  

   import java io IOException;

   import ServerSocket;

   import Socket;

  

   import testmutithreadserver old threadpool ThreadPool;

  

   /**

     * 简单阻塞式多线程服务器(线程池处理)

     *

     * @author zhangjun

     *

     */

   public class Server

  

        private int port;

  

        private ServerSocket serverSocket;

  

        private ThreadPool threadPool;

  

        private PortListenThread listener;

  

        public Server(int port)

            this port = port;

            threadPool = new ThreadPool();

       

  

        public void start()

            try

                serverSocket = new ServerSocket(port);

                listener = new PortListenThread();

                listener start();

            catch (IOException e)

                e printStackTrace();

           

       

  

        public void shutdown()

            threadPool shutdown();

            listener finish();

       

  

        private class PortListenThread extends Thread

  

            private Boolean finish = false;

  

            @Override

            public void run()

                while (!finish)

                    try

                        final Socket socket = serverSocket accept();

                        threadPool execute(new Runnable()

  

                            @Override

                            public void run()

                                new TestMessage(socket) execute();

                           

                        );

                    catch (IOException e)

                        e printStackTrace();

                   

  

               

           

  

            public void finish()

                finish = true;

           

  

       

  

        public static void main(String[] args)

            int port = ;

            System out println( server is listening on port: + port);

            new Server(port) start();

       

  

  

  

  这个Server调用的是自己实现的一个基于任务队列的简单线程池

   package testmutithreadserver old threadpool;

  

   import java util LinkedList;

  

   /**

     * 简单线程池 (基于工作队列的同步线程池)

     *

     * @author zhangjun

     *

     */

   public class ThreadPool extends ThreadGroup

        private final static String THREADPOOL = thread pool ;

        private final static String WORKTHREAD = work thread ;

        private final static int DEFAULTSIZE = Runtime getRuntime()

                availableProcessors() + ;

        private LinkedList<Runnable> taskQueue;

        private boolean isPoolClose = false;

  

        public ThreadPool()

            this(DEFAULTSIZE);

       

  

        public ThreadPool(int size)

            super(THREADPOOL);

            setDaemon(true);

            taskQueue = new LinkedList<Runnable>();

            initWorkThread(size);

       

  

        private void initWorkThread(int size)

            for (int i = ; i < size; i++)

                new WorkThread(WORKTHREAD + i) start();

           

            try

                Thread sleep( * size);

            catch (InterruptedException e)

           

       

  

        public synchronized void execute(Runnable task)

            if (isPoolClose)

                throw new IllegalStateException();

           

            if (task != null)

                taskQueue add(task);

                notify();

           

       

  

        private synchronized Runnable getTask() throws InterruptedException

            if (taskQueue size() == )

                if (isPoolClose)

                    return null;

               

                wait();

           

            if (taskQueue size() == )

                return null;

           

            return taskQueue removeFirst();

       

  

        public void shutdown()

            waitFinish();

            synchronized (this)

                isPoolClose = true;

                interrupt();

                taskQueue clear();

           

       

  

        private void waitFinish()

            synchronized (this)

                isPoolClose = true;

                notifyAll();

           

            Thread[] threads = new Thread[activeCount()];

            enumerate(threads);

            try

                for (Thread t : threads)

                    t join();

               

            catch (InterruptedException e)

                //swallow this

           

       

  

        private class WorkThread extends Thread

  

            public WorkThread(String name)

                super(ThreadPool this name);

           

  

            @Override

            public void run()

                while (!isInterrupted())

                    Runnable task = null;

                    try

                        task = getTask();

                    catch (InterruptedException e)

                        //swallow this

                   

                    if (task == null)

                        return;

                   

                    try

                        task run();

                    catch (Throwable e)

                        e printStackTrace();

                   

               

           

  

       

  

  

  当然也可以直接使用concurrent的线程池 代码几乎不用改变

   package testncurrent;

  

   import java io IOException;

   import ServerSocket;

   import Socket;

   import ncurrent ExecutorService;

   import ncurrent Executors;

  

   import testmutithreadserver old TestMessage;

  

   /**

     * 简单阻塞式多线程服务器(线程池处理)

     *

     * @author zhangjun

     *

     */

   public class Server

  

        private int port;

  

        private ServerSocket serverSocket;

  

        private ExecutorService threadPool;

  

        private PortListenThread listener;

  

        public Server(int port)

            this port = port;

            threadPool = Executors newFixedThreadPool( );

       

  

        public void start()

            try

                serverSocket = new ServerSocket(port);

                listener = new PortListenThread();

                listener start();

            catch (IOException e)

                e printStackTrace();

           

       

  

        public void shutdown()

            threadPool shutdown();

            listener finish();

       

  

        private class PortListenThread extends Thread

  

            private Boolean finish = false;

  

            @Override

            public void run()

                while (!finish)

                    try

                        final Socket socket = serverSocket accept();

                        threadPool execute(new Runnable()

  

                            @Override

                            public void run()

                                new TestMessage(socket) execute();

                           

                        );

                    catch (IOException e)

                        e printStackTrace();

                   

  

               

           

  

            public void finish()

                finish = true;

           

  

       

  

        public static void main(String[] args)

            int port = ;

            System out println( server is listening on port: + port);

            new Server(port) start();

       

  

  

  里边我构造了一个Message接口

   package testmutithreadserver old;

  

   /**

     * 通用消息接口

     *

     * @author zhangjun

     *

     */

   public interface Message

  

        void execute();

  

  

  

  以及实现了一个测试消息类

   package testmutithreadserver old;

  

   import java io BufferedReader;

   import java io IOException;

   import java io InputStreamReader;

   import java io PrintWriter;

   import Socket;

  

   /**

     * 测试消息

     *

     * @author zhangjun

     *

     */

   public class TestMessage implements Message

  

        private Socket socket;

  

        public TestMessage(Socket socket)

            this socket = socket;

       

  

        @Override

        public void execute()

            try

                BufferedReader in = new BufferedReader(new InputStreamReader(socket

                        getInputStream()));

                PrintWriter out = new PrintWriter(socket getOutputStream() true);

                String s;

                while ((s = in readLine()) != null)

                    System out println( received message: + s);

                    if (s equals( quit ))

                        break;

                   

                    out println( hello + s);

               

            catch (IOException e)

                e printStackTrace();

            finally

                try

                    if (!socket isClosed())

                        socket close();

                   

                catch (IOException e)

               

           

       

  

  

  

cha138/Article/program/Java/gj/201311/27312

相关参考

知识大全 一个非常简单和短小的线程池

    最近写了一个HTTP代理服务器发现访问网页时建立的连接很多消耗的线程也非常的多对于系统是一个不小的开销而且这些线程存在的时间都很短%以上的线程存在的时间

知识大全 Java学习:线程池的简单构建

Java学习:线程池的简单构建  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  现在服务器端的应用

知识大全 用Java实现多线程服务器程序

用Java实现多线程服务器程序  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  摘要在Java出现

知识大全 Java Socket多线程如何支持服务器模型

JavaSocket多线程如何支持服务器模型  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  Ja

知识大全 使用JAVA建立稳定的多线程服务器

使用JAVA建立稳定的多线程服务器  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! &nb

知识大全 加入多线程[2]

疯狂Java讲义:加入多线程[2]  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  当服务器线程读

知识大全 Java Socket多线程服务端、客户端

JavaSocket多线程服务端、客户端  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  //主方

知识大全 java关于多线程的部分操作

  一般服务器端代码每次收到一个线程一个client就会产生  /************************开始监听**************************/  intport=; 

知识大全 Java多线程Socket操作猜数游戏样例

Java多线程Socket操作猜数游戏样例  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  服务器

知识大全 多线程从线程继承

    为创建一个线程最简单的方法就是从Thread类继承这个类包含了创建和运行线程所需的一切东西Thread最重要的方法是run()但为了使用run()必须对其进行过载或者覆蓋使其能充分按自己的吩咐