我的应用程序中有一个自制的网络服务器。此 Web 服务器为进入套接字的每个请求生成一个新线程以被接受。我希望网络服务器等到它刚刚创建的线程中的特定点被命中。
我已经浏览了该网站上的许多帖子和网络上的示例,但是在我告诉线程等待后无法让网络服务器继续进行。一个基本的代码示例会很棒。
同步关键字是解决此问题的正确方法吗?如果是这样,如何实现?我的应用程序的代码示例如下:
网络服务器
while (true) {
//block here until a connection request is made
socket = server_socket.accept();
try {
//create a new HTTPRequest object for every file request
HttpRequest request = new HttpRequest(socket, this);
//create a new thread for each request
Thread thread = new Thread(request);
//run the thread and have it return after complete
thread.run();
///////////////////////////////
wait here until notifed to proceed
///////////////////////////////
} catch (Exception e) {
e.printStackTrace(logFile);
}
}
线程代码
public void run() {
//code here
//notify web server to continue here
}
更新 - 最终代码如下。每当我发送响应标头时都会调用(当然还将接口添加为单独的类和中的HttpRequest
方法):resumeListener.resume()
addResumeListener(ResumeListener r1)
HttpRequest
网络服务器部分
// server infinite loop
while (true) {
//block here until a connection request is made
socket = server_socket.accept();
try {
final Object locker = new Object();
//create a new HTTPRequest object for every file request
HttpRequest request = new HttpRequest(socket, this);
request.addResumeListener(new ResumeListener() {
public void resume() {
//get control of the lock and release the server
synchronized(locker) {
locker.notify();
}
}
});
synchronized(locker) {
//create a new thread for each request
Thread thread = new Thread(request);
//run the thread and have it return after complete
thread.start();
//tell this thread to wait until HttpRequest releases
//the server
locker.wait();
}
} catch (Exception e) {
e.printStackTrace(Session.logFile);
}
}