gpt4 book ai didi

java - Java Web 服务器中的线程池

转载 作者:行者123 更新时间:2023-11-29 03:20:28 24 4
gpt4 key购买 nike

我有我的多线程网络服务器,现在我想实现一个线程池,但是即使看了之后我还是不知道如何在我的代码中实现它:(

有人可以帮我改进一下吗?我真的需要了解如何在此处使用我阅读的内容,因为我看不到连接以及它是如何工作的。

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;


public class WebServer {

static class RequisicaoRunnable implements Runnable {

private Socket socket;

RequisicaoRunnable(Socket socket) {
this.socket = socket;
}

@Override
public void run() {
try {
//System.out.println("connection from " + socket.getInetAddress().getHostName());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//System.out.println("READING SOCKET...");
String str = in.readLine();
String[] arr = str.split(" ");
if (arr != null && arr.length > 2) {
while(!str.equals("")) {
//System.out.println(str);
str = in.readLine();
}
if (arr[0].equals("GET")) {
//System.out.println("REQUESTED RESOURCE: " + arr[1]);
String nomeArquivo = arr[1];
if (arr[1].startsWith("/")) {
nomeArquivo = nomeArquivo.substring(1);
}
if (nomeArquivo.equals("")) {
nomeArquivo = "index.html";
}
File f = new File(nomeArquivo);
if (f.exists()) {
FileInputStream fin = new FileInputStream(f);
socket.getOutputStream().write("HTTP/1.0 200 OK\n\n".getBytes());
byte[] buffer = new byte[1024];
int lidos;
do {
lidos = fin.read(buffer);
if (lidos > 0) {
socket.getOutputStream().write(buffer, 0, lidos);
}
} while (lidos > 0);
fin.close();
} else {
socket.getOutputStream().write("HTTP/1.0 404 Not Found\n\n".getBytes());
socket.getOutputStream().write("<html><body>HTTP/1.0 404 File Not Found</body></html>\n\n".getBytes());
}
} else {
socket.getOutputStream().write("HTTP/1.0 501 Not Implemented\n\n".getBytes());
}
}
socket.close();
} catch (IOException e) { }
}
}

public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("waiting connections....");
while (true) {
Socket socket = serverSocket.accept();
RequisicaoRunnable req = new RequisicaoRunnable(socket);
new Thread(req).start();
}
}

}

最佳答案

线程池背后的思想是在启动时创建指定数量的线程,然后将任务分配给它们。 或者消除每次创建线程的麻烦。几天前我实现了它,这是我所做的。

  1. 在开始时创建一些线程,它们共享一个请求队列
  2. 线程不断地寻找队列,当一个请求到来时线程调度请求并执行操作
  3. 队列将同步 3.

下面是一些队列方法

Queue#add();    //add the socket at the end
Queue#removeFront();//remove socket
Queue#isEmpty();//boolean if queue is empty
Queue#size(); //return size of queue
Queue#getMaxSize();//get maximum allowed size for queue

您的请求处理可运行

public class Processor implements Runnable {

private Queue<Socket> requests;
private boolean shut;

Processor(Queue<Socket> requests) {
this.requests = requests;
shut = false;
}

@Override
public void run() {
while(!shut) {
if(requests.isEmpty()) {
try{
Thread.sleep(#rendomeTimemill);
} catch(InterruptedException e){}
}else {
Socket skt = Queue.removeFront();
try {
//System.out.println("processing request from " + socket.getInetAddress().getHostName());
//do you want
} catch (Exception e) {
} finally {
if(skt != null) {
try{ skt.close(); skt = null; } catch(IOException ex){}

}
}
}
}
}
public void stopNow() {
shut = true;
Thread.interrupt();
}
}

在你的主线程中创建一个队列来放置请求

//start your server socket
Queue<Socket> requests = new Queue<Socket>();

启动工作线程池

Precessor []workers = new Processor[NUM_WORKER];
for(int i=0;i<NUM_WORKER; i++) {
worker[i] = new Processor(requests);
Thread th = new Thread(worker[i]);
th.strat();
}

请求监听

//while loope that run forever
// accept socket
if(requests.size() == requests.getMaxSize()) {
socket.getOutputStream().write("HTTP/1.0 505 Error\n\n".getBytes());
socket.getOutputStream().write("<html><body>Try again</body></html>\n\n".getBytes());
socket.close();
} else {
requests.add(socket);
}

当你想关闭服务器时

for(int i=0;i<NUM_WORKER; i++) {
worker[i].stopNow();
}

注意:我关心的不是 HTTP header ,所以我不具体,但您必须实现完整的 HTTP header ,例如内容类型、内容长度等

关于java - Java Web 服务器中的线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23962359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com