java类库中的多线程

本文介绍如何利用JDK中的线程池特性,通过ExecutorService接口及其子接口来实现一个基本的HTTP服务器,包括服务器启动、监听客户端连接、响应请求等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JDK类库中的线程池
.
分类: J2EE2012-10-16 12:44162人阅读评论(0)收藏举报

jdkexceptionhttp服务器bufferstringsocket




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



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



[java] view plaincopyprint?
01.package http;
02.
03.import java.io.FileInputStream;
04.import java.io.IOException;
05.import java.net.InetSocketAddress;
06.import java.net.Socket;
07.import java.nio.ByteBuffer;
08.import java.nio.CharBuffer;
09.import java.nio.channels.FileChannel;
10.import java.nio.channels.ServerSocketChannel;
11.import java.nio.channels.SocketChannel;
12.import java.nio.charset.Charset;
13.import java.util.concurrent.ExecutorService;
14.import java.util.concurrent.Executors;
15.
16.public class SimpleHttpServer {
17. private int port=80;
18. private ServerSocketChannel serverSocketChannel=null;
19. private ExecutorService executorService;
20. private static final int POOL_MULTIPLE=4;
21. private Charset charset=Charset.forName("utf-8");
22. public SimpleHttpServer() throws IOException{
23. executorService =Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_MULTIPLE);
24. serverSocketChannel=ServerSocketChannel.open();
25. serverSocketChannel.socket().setReuseAddress(true);
26. serverSocketChannel.socket().bind(new InetSocketAddress(port));
27. System.out.println("服务器启动");
28. }
29. public void service(){
30. while(true){
31. SocketChannel socketChannel=null;
32. try {
33. socketChannel=serverSocketChannel.accept();
34. executorService.execute(new Handler(socketChannel));
35. } catch (Exception e) {
36. e.printStackTrace();
37. }
38. }
39. }
40. public static void main(String[] args) throws IOException {
41. new SimpleHttpServer().service();
42. }
43. class Handler implements Runnable{
44. private SocketChannel socketChannel;
45. public Handler(SocketChannel socketChannel){
46. this.socketChannel=socketChannel;
47. }
48. public void run(){
49. handle(socketChannel);
50. }
51. public void handle(SocketChannel socketChannel){
52. try {
53. Socket socket=socketChannel.socket();
54. System.out.println("received client's connection come from "+socket.getInetAddress()+":"+socket.getPort());
55. ByteBuffer buffer=ByteBuffer.allocate(2048);//accept http request,assume the request's length less than 2048
56. socketChannel.read(buffer);
57. buffer.flip();
58. String request=decode(buffer);
59. System.out.println(request); //print the http reqeust
60. //construct http response
61. StringBuffer sb=new StringBuffer("HTTP/1.1 200 OK\r\n");
62. sb.append("Content-Type:text/html\r\n\r\n");
63. socketChannel.write(encode(sb.toString()));
64.
65. FileInputStream in;
66. //get the http request's first line
67. String firstLineOfRequest=request.substring(0,request.indexOf("\r\n"));
68. if(firstLineOfRequest.indexOf("login.html")!=-1){
69. in=new FileInputStream("D:\\work\\workspace\\myjava\\src\\http\\login.html");
70. }else{
71. in=new FileInputStream("D:\\work\\workspace\\myjava\\src\\http\\hello.html");
72. }
73. FileChannel fileChannel=in.getChannel();
74. fileChannel.transferTo(0, fileChannel.size(), socketChannel);//send response
75. } catch (Exception e) {
76. e.printStackTrace();
77. }finally{
78. try {
79. if(socketChannel!=null){
80. socketChannel.close();
81. }
82. } catch (Exception e2) {
83. e2.printStackTrace();
84. }
85. }
86. }
87. public String decode(ByteBuffer buffer){
88. CharBuffer charBuffer=charset.decode(buffer);
89. return charBuffer.toString();
90. }
91. public ByteBuffer encode(String str){
92. return charset.encode(str);
93. }
94. }
95.}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值