Java 线程池学习--线程池实例讲解

来源:互联网 发布:阿里云ecs远程桌面 编辑:程序博客网 时间:2024/06/07 17:13
Java5增加了新的类库并发集java.util.concurrent,该类库为并发程序提供了丰富的API多线程编程在Java 5中更加容易,灵活。本文通过一个网络服务器模型,来实践Java5的多线程编程,该模型中使用了Java5中的线程池,阻塞队列,可重入锁等,还实践了Callable, Future等接口,并使用了Java 5的另外一个新特性泛型。 

  简介 

  本文将实现一个网络服务器模型,一旦有客户端连接到该服务器,则启动一个新线程为该连接服务,服务内容为往客户端输送一些字符信息。一个典型的网络服务器模型如下: 

  1. 建立监听端口。 

  2. 发现有新连接,接受连接,启动线程,执行服务线程。 3. 服务完毕,关闭线程。 

  这个模型在大部分情况下运行良好,但是需要频繁的处理用户请求而每次请求需要的服务又是简短的时候,系统会将大量的时间花费在线程的创建销毁。Java 5的线程池克服了这些缺点。通过对重用线程来执行多个任务,避免了频繁线程的创建与销毁开销,使得服务器的性能方面得到很大提高。因此,本文的网络服务器模型将如下: 

  1. 建立监听端口,创建线程池。 

  2. 发现有新连接,使用线程池来执行服务任务。 

  3. 服务完毕,释放线程到线程池。 

  下面详细介绍如何使用Java 5的concurrent包提供的API来实现该服务器。 

  初始化 

  初始化包括创建线程池以及初始化监听端口。创建线程池可以通过调用java.util.concurrent.Executors类里的静态方法newChahedThreadPool或是newFixedThreadPool来创建,也可以通过新建一个java.util.concurrent.ThreadPoolExecutor实例来执行任务。这里我们采用newFixedThreadPool方法来建立线程池。 

ExecutorService pool = Executors.newFixedThreadPool(10); 

  表示新建了一个线程池,线程池里面有10个线程为任务队列服务。 

  使用ServerSocket对象来初始化监听端口。 

private static final int PORT = 19527; 
serverListenSocket = new ServerSocket(PORT); 
serverListenSocket.setReuseAddress(true); 
serverListenSocket.setReuseAddress(true); 

  服务新连接 

  当有新连接建立时,accept返回时,将服务任务提交给线程池执行。 

while(true){ 
 Socket socket = serverListenSocket.accept(); 
 pool.execute(new ServiceThread(socket)); 


  这里使用线程池对象来执行线程,减少了每次线程创建和销毁的开销。任务执行完毕,线程释放到线程池。 

  服务任务 

  服务线程ServiceThread维护一个count来记录服务线程被调用的次数。每当服务任务被调用一次时,count的值自增1,因此ServiceThread提供一个increaseCount和getCount的方法,分别将count值自增1和取得该count值。由于可能多个线程存在竞争,同时访问count,因此需要加锁机制,在Java 5之前,我们只能使用synchronized来锁定。Java 5中引入了性能更加粒度更细的重入锁ReentrantLock。我们使用ReentrantLock保证代码线程安全。下面是具体代码: 

private static ReentrantLock lock = new ReentrantLock (); 
private static int count = 0; 
private int getCount(){ 
 int ret = 0; 
 try{ 
  lock.lock(); 
  ret = count; 
 }finally{ 
  lock.unlock(); 
 } 
 return ret; 

private void increaseCount(){ 
 try{ 
  lock.lock(); 
  ++count; 
 }finally{ 
  lock.unlock(); 
 } 


  服务线程在开始给客户端打印一个欢迎信息, 

increaseCount(); 
int curCount = getCount(); 
helloString = "hello, id = " + curCount+"\r\n"; 
dos = new DataOutputStream(connectedSocket.getOutputStream()); 
dos.write(helloString.getBytes()); 

  然后使用ExecutorService的submit方法提交一个Callable的任务,返回一个Future接口的引用。这种做法对费时的任务非常有效,submit任务之后可以继续执行下面的代码,然后在适当的位置可以使用Future的get方法来获取结果,如果这时候该方法已经执行完毕,则无需等待即可获得结果,如果还在执行,则等待到运行完毕。 

ExecutorService executor = Executors.newSingleThreadExecutor(); 
Future future = executor.submit(new TimeConsumingTask()); 
dos.write("let's do soemthing other".getBytes()); 
String result = future.get(); 
dos.write(result.getBytes()); 

  其中TimeConsumingTask实现了Callable接口 

class TimeConsumingTask implements Callable { 
 public String call() throws Exception { 
  System.out.println("It's a time-consuming task, you'd better retrieve your result in the furture"); 
  return "ok, here's the result: It takes me lots of time to produce this result"; 
 } 


  这里使用了Java 5的另外一个新特性泛型,声明TimeConsumingTask的时候使用了String做为类型参数。必须实现Callable接口的call函数,其作用类似与Runnable中的run函数,在call函数里写入要执行的代码,其返回值类型等同于在类声明中传入的类型值。在这段程序中,我们提交了一个Callable的任务,然后程序不会堵塞,而是继续执行dos.write("let's do soemthing other".getBytes());当程序执行到String result = future.get()时如果call函数已经执行完毕,则取得返回值,如果还在执行,则等待其执行完毕。 

服务器端的完整实现 

  服务器端的完整实现代码如下: 
Java代码  收藏代码
  1. package demo;  
  2.   
  3. import java.io.DataOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.Serializable;  
  6. import java.net.ServerSocket;  
  7. import java.net.Socket;  
  8. import java.util.concurrent.ArrayBlockingQueue;  
  9. import java.util.concurrent.BlockingQueue;  
  10. import java.util.concurrent.Callable;  
  11. import java.util.concurrent.ExecutionException;  
  12. import java.util.concurrent.ExecutorService;  
  13. import java.util.concurrent.Executors;  
  14. import java.util.concurrent.Future;  
  15. import java.util.concurrent.RejectedExecutionHandler;  
  16. import java.util.concurrent.ThreadPoolExecutor;  
  17. import java.util.concurrent.TimeUnit;  
  18. import java.util.concurrent.locks.ReentrantLock;  
  19.   
  20. public class Server  
  21. {  
  22.     private static int produceTaskSleepTime = 100;  
  23.     private static int consumeTaskSleepTime = 1200;  
  24.     private static int produceTaskMaxNumber = 100;  
  25.     private static final int CORE_POOL_SIZE = 2;  
  26.     private static final int MAX_POOL_SIZE = 100;  
  27.     private static final int KEEPALIVE_TIME = 3;  
  28.     private static final int QUEUE_CAPACITY = (CORE_POOL_SIZE + MAX_POOL_SIZE) / 2;  
  29.     private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;  
  30.     private static final String HOST = "127.0.0.1";  
  31.     private static final int PORT = 19527;  
  32.     private BlockingQueue workQueue = new ArrayBlockingQueue(QUEUE_CAPACITY);  
  33.     // private ThreadPoolExecutor serverThreadPool = null;  
  34.     private ExecutorService pool = null;  
  35.     private RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy();  
  36.     private ServerSocket serverListenSocket = null;  
  37.     private int times = 5;  
  38.   
  39.     public void start()  
  40.     {  
  41.         // You can also init thread pool in this way.  
  42.         /* 
  43.          * serverThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEPALIVE_TIME, TIME_UNIT, workQueue, rejectedExecutionHandler); 
  44.          */  
  45.         pool = Executors.newFixedThreadPool(10);  
  46.         try  
  47.         {  
  48.             serverListenSocket = new ServerSocket(PORT);  
  49.             serverListenSocket.setReuseAddress(true);  
  50.   
  51.             System.out.println("I'm listening");  
  52.             while (times-- > 0)  
  53.             {  
  54.                 Socket socket = serverListenSocket.accept();  
  55.                 String welcomeString = "hello";  
  56.                 // serverThreadPool.execute(new ServiceThread(socket, welcomeString));  
  57.                 pool.execute(new ServiceThread(socket));  
  58.             }  
  59.         }  
  60.         catch (IOException e)  
  61.         {  
  62.             // TODO Auto-generated catch block  
  63.             e.printStackTrace();  
  64.         }  
  65.         cleanup();  
  66.     }  
  67.   
  68.     public void cleanup()  
  69.     {  
  70.         if (null != serverListenSocket)  
  71.         {  
  72.             try  
  73.             {  
  74.                 serverListenSocket.close();  
  75.             }  
  76.             catch (IOException e)  
  77.             {  
  78.                 // TODO Auto-generated catch block  
  79.                 e.printStackTrace();  
  80.             }  
  81.         }  
  82.         // serverThreadPool.shutdown();  
  83.         pool.shutdown();  
  84.        //调用 shutdown() 方法之后,主线程就马上结束了,而线程池会继续运行直到所有任务执行完才会停止。如果不调用 shutdown() 方法,那么线程池会一直保持下去,以便随时添加新的任务。interrupt():只有阻塞(sleep,wait,join的线程调用他们的interrupt()才起作用,正在运行的线程不起作用也不抛异常)  
  85.     }  
  86.   
  87.     public static void main(String args[])  
  88.     {  
  89.         Server server = new Server();  
  90.         server.start();  
  91.     }  
  92. }  
  93.   
  94. class ServiceThread implements Runnable, Serializable  
  95. {  
  96.     private static final long serialVersionUID = 0;  
  97.     private Socket connectedSocket = null;  
  98.     private String helloString = null;  
  99.     private static int count = 0;  
  100.     private static ReentrantLock lock = new ReentrantLock();  
  101.   
  102.     ServiceThread(Socket socket)  
  103.     {  
  104.         connectedSocket = socket;  
  105.     }  
  106.   
  107.     public void run()  
  108.     {  
  109.         increaseCount();  
  110.         int curCount = getCount();  
  111.         helloString = "hello, id = " + curCount + "\r\n";  
  112.   
  113.         ExecutorService executor = Executors.newSingleThreadExecutor();  
  114.         Future<String> future = executor.submit(new TimeConsumingTask());  
  115.   
  116.         DataOutputStream dos = null;  
  117.         try  
  118.         {  
  119.             dos = new DataOutputStream(connectedSocket.getOutputStream());  
  120.             dos.write(helloString.getBytes());  
  121.             try  
  122.             {  
  123.                 dos.write("let's do soemthing other.\r\n".getBytes());  
  124.                 String result = future.get();  
  125.                 dos.write(result.getBytes());  
  126.             }  
  127.             catch (InterruptedException e)  
  128.             {  
  129.                 e.printStackTrace();  
  130.             }  
  131.             catch (ExecutionException e)  
  132.             {  
  133.                 e.printStackTrace();  
  134.             }  
  135.         }  
  136.         catch (IOException e)  
  137.         {  
  138.             // TODO Auto-generated catch block  
  139.             e.printStackTrace();  
  140.         }  
  141.         finally  
  142.         {  
  143.             if (null != connectedSocket)  
  144.             {  
  145.                 try  
  146.                 {  
  147.                     connectedSocket.close();  
  148.                 }  
  149.                 catch (IOException e)  
  150.                 {  
  151.                     // TODO Auto-generated catch block  
  152.                     e.printStackTrace();  
  153.                 }  
  154.             }  
  155.             if (null != dos)  
  156.             {  
  157.                 try  
  158.                 {  
  159.                     dos.close();  
  160.                 }  
  161.                 catch (IOException e)  
  162.                 {  
  163.                     // TODO Auto-generated catch block  
  164.                     e.printStackTrace();  
  165.                 }  
  166.             }  
  167.             executor.shutdown();  
  168.         }  
  169.     }  
  170.   
  171.     private int getCount()  
  172.     {  
  173.         int ret = 0;  
  174.         try  
  175.         {  
  176.             lock.lock();  
  177.             ret = count;  
  178.         }  
  179.         finally  
  180.         {  
  181.             lock.unlock();  
  182.         }  
  183.         return ret;  
  184.     }  
  185.   
  186.     private void increaseCount()  
  187.     {  
  188.         try  
  189.         {  
  190.             lock.lock();  
  191.             ++count;  
  192.         }  
  193.         finally  
  194.         {  
  195.             lock.unlock();  
  196.         }  
  197.     }  
  198. }  
  199.   
  200. class TimeConsumingTask implements Callable<String>  
  201. {  
  202.     public String call() throws Exception  
  203.     {  
  204.         System.out.println("It's a time-consuming task, you'd better retrieve your result in the furture");  
  205.         return "ok, here's the result: It takes me lots of time to produce this result";  
  206.     }  
  207.   
  208. }  
0 0
原创粉丝点击