服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 核心技术 > 查看文档

java 5.0 多线程编程实践

  java5增加了新的类库并发集java.util.concurrent,该类库为并发程序提供了丰富的api多线程编程在java 5中更加容易,灵活。本文通过一个网络服务器模型,来实践java5的多线程编程,该模型中使用了java5中的线程池,阻塞队列,可重入锁等,还实践了callable, future等接口,并使用了java 5的另外一个新特性泛型。

  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 <string> 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 <string>{
 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函数已经执行完毕,则取得返回值,如果还在执行,则等待其执行完毕。

  服务器端的完整实现

  服务器端的完整实现代码如下:

package com.andrew;

import java.io.dataoutputstream;
import java.io.ioexception;
import java.io.serializable;
import java.net.serversocket;
import java.net.socket;
import java.util.concurrent.arrayblockingqueue;
import java.util.concurrent.blockingqueue;
import java.util.concurrent.callable;
import java.util.concurrent.executionexception;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.future;
import java.util.concurrent.rejectedexecutionhandler;
import java.util.concurrent.threadpoolexecutor;
import java.util.concurrent.timeunit;
import java.util.concurrent.locks.reentrantlock;

public class server {
 private static int producetasksleeptime = 100;
 private static int consumetasksleeptime = 1200;
 private static int producetaskmaxnumber = 100;
 private static final int core_pool_size = 2;
 private static final int max_pool_size = 100;
 private static final int keepalive_time = 3;
 private static final int queue_capacity = (core_pool_size + max_pool_size) / 2;
 private static final timeunit time_unit = timeunit.seconds;
 private static final string host = "127.0.0.1";
 private static final int port = 19527;
 private blockingqueue<runnable> workqueue = new arrayblockingqueue<runnable>(queue_capacity);
 //private threadpoolexecutor serverthreadpool = null;
 private executorservice pool = null;
 private rejectedexecutionhandler rejectedexecutionhandler = new threadpoolexecutor.discardoldestpolicy();
 private serversocket serverlistensocket = null;
 private int times = 5;
 public void start() {
  // you can also init thread pool in this way.
  /*serverthreadpool = new threadpoolexecutor(core_pool_size,
  max_pool_size, keepalive_time, time_unit, workqueue,
  rejectedexecutionhandler);*/
  pool = executors.newfixedthreadpool(10);
  try {
   serverlistensocket = new serversocket(port);
   serverlistensocket.setreuseaddress(true);

   system.out.println("i'm listening");
   while (times-- > 0) {
    socket socket = serverlistensocket.accept();
    string welcomestring = "hello";
    //serverthreadpool.execute(new servicethread(socket, welcomestring));
    pool.execute(new servicethread(socket));
   }
  } catch (ioexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
  cleanup();
 }

 public void cleanup() {
  if (null != serverlistensocket) {
   try {
    serverlistensocket.close();
   } catch (ioexception e) {
    // todo auto-generated catch block
    e.printstacktrace();
   }
  }
  //serverthreadpool.shutdown();
  pool.shutdown();
 }

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

class servicethread implements runnable, serializable {
 private static final long serialversionuid = 0;
 private socket connectedsocket = null;
 private string hellostring = null;
 private static int count = 0;
 private static reentrantlock lock = new reentrantlock();

 servicethread(socket socket) {
  connectedsocket = socket;
 }

 public void run() {
  increasecount();
  int curcount = getcount();
  hellostring = "hello, id = " + curcount + "\r\n";

  executorservice executor = executors.newsinglethreadexecutor();
  future<string> future = executor.submit(new timeconsumingtask());

  dataoutputstream dos = null;
  try {
   dos = new dataoutputstream(connectedsocket.getoutputstream());
   dos.write(hellostring.getbytes());
   try {
    dos.write("let's do soemthing other.\r\n".getbytes());
    string result = future.get();
    dos.write(result.getbytes());
   } catch (interruptedexception e) {
    e.printstacktrace();
   } catch (executionexception e) {
    e.printstacktrace();
   }
  } catch (ioexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  } finally {
   if (null != connectedsocket) {
    try {
     connectedsocket.close();
    } catch (ioexception e) {
     // todo auto-generated catch block
     e.printstacktrace();
    }
   }
   if (null != dos) {
    try {
     dos.close();
    } catch (ioexception e) {
     // todo auto-generated catch block
     e.printstacktrace();
    }
   }
   executor.shutdown();
  }
 }

 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();
  }
 }
}

class timeconsumingtask implements callable<string> {
 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";
 }

}

  运行程序

  运行服务端,客户端只需使用telnet 127.0.0.1 19527 即可看到信息如下:

扫描关注微信公众号