JDK类库中的线程池

来源:互联网 发布:js 监听dom变化 编辑:程序博客网 时间:2024/05/29 17:16


Executor接口表示线程池,它的executor(Runnabletask)方法用来执行Runnable类型的任务。Executor的子接口ExecutorService中声明了管理线程池的一些方法,比如用于关闭线程池的shutdown()方法等,Executors类中包含了一些静态方法,它们负责生成各种类型的线程池ExecutorService实例.

例子:简单http服务器(阻塞模式)

package http;import java.io.FileInputStream;import java.io.IOException;import java.net.InetSocketAddress;import java.net.Socket;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.nio.channels.FileChannel;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.nio.charset.Charset;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class SimpleHttpServer {private int port=80;private ServerSocketChannel serverSocketChannel=null;private ExecutorService executorService;private static final int POOL_MULTIPLE=4;private Charset charset=Charset.forName("utf-8");public SimpleHttpServer() throws IOException{executorService =Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_MULTIPLE);serverSocketChannel=ServerSocketChannel.open();serverSocketChannel.socket().setReuseAddress(true);serverSocketChannel.socket().bind(new InetSocketAddress(port));System.out.println("服务器启动");}public void service(){while(true){SocketChannel socketChannel=null;try {socketChannel=serverSocketChannel.accept();executorService.execute(new Handler(socketChannel));} catch (Exception e) {e.printStackTrace();}}}public static void main(String[] args) throws IOException {new SimpleHttpServer().service();}class Handler implements Runnable{private SocketChannel socketChannel;public Handler(SocketChannel socketChannel){this.socketChannel=socketChannel;}public void run(){handle(socketChannel);}public void handle(SocketChannel socketChannel){try {Socket socket=socketChannel.socket();System.out.println("received client's connection come from "+socket.getInetAddress()+":"+socket.getPort());ByteBuffer buffer=ByteBuffer.allocate(2048);//accept http request,assume the request's length less than 2048socketChannel.read(buffer);buffer.flip();String request=decode(buffer);System.out.println(request); //print the http reqeust//construct http responseStringBuffer sb=new StringBuffer("HTTP/1.1 200 OK\r\n");sb.append("Content-Type:text/html\r\n\r\n");socketChannel.write(encode(sb.toString()));FileInputStream in;//get the http request's first lineString firstLineOfRequest=request.substring(0,request.indexOf("\r\n"));if(firstLineOfRequest.indexOf("login.html")!=-1){in=new FileInputStream("D:\\work\\workspace\\myjava\\src\\http\\login.html");}else{in=new FileInputStream("D:\\work\\workspace\\myjava\\src\\http\\hello.html");}FileChannel fileChannel=in.getChannel();fileChannel.transferTo(0, fileChannel.size(), socketChannel);//send response} catch (Exception e) {e.printStackTrace();}finally{try {if(socketChannel!=null){socketChannel.close();}} catch (Exception e2) {e2.printStackTrace();}}}public String decode(ByteBuffer buffer){CharBuffer charBuffer=charset.decode(buffer);return charBuffer.toString();}public ByteBuffer encode(String str){return charset.encode(str);}}}


原创粉丝点击