アプリに自家製の Web サーバーがあります。この Web サーバーは、受け入れられるソケットに入ってくるすべての要求に対して新しいスレッドを生成します。作成したばかりのスレッドで特定のポイントに到達するまで Web サーバーを待機させたい。
このサイトの多くの投稿と Web 上の例を確認しましたが、スレッドに待機するように指示した後、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
Web サーバー部分
// 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);
}
}