동기화 실 Java
-
05-07-2019 - |
문제
나는 가장 웹 서버에 표시합니다.이 웹 서버는 새로운 스레드를 위해 모든 요청으로 제공되는 소켓을 받아들여집니다.나는 원하는 웹 서버를 기다릴까지 특정 시점중에서 스레드 그것은 단지 만들어집니다.
을 통해되었습니다 이 사이트에 많은 게시물 및 예 웹에서만 얻을 수 없는 웹 서버를 진행한 후에 말레드를 기다립니다.기본 코드 예제에서 좋은 것입니다.
은 동기화된 키워드는 올바른 방법에 대해 이동하는 이?그렇다면,이것은 어떻게 달성 할 수 있는?코드 예제는 아래의 내용:
웹 서버
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);
}
}
해결책
먼저,저는 감정의 다른 사람 다시 바퀴를 발명하기에 이어질 가능성이 가장 높은 다양한 문제에 대한 당신.그러나,당신이 가고 싶다면 아래로 이 도로는 어쨌든 무엇을 하려고 하는 것은 어렵지 않습니다.당신은 실험 Jetty?
어쩌면 뭔가 다음과 같다:
public class MyWebServer {
public void foo() throws IOException {
while (true) {
//block here until a connection request is made
ServerSocket socket = new ServerSocket();
try {
final Object locker = new Object();
//create a new HTTPRequest object for every file request
MyRequest request = new MyRequest(socket);
request.addResumeListener(new ResumeListener() {
public void resume() {
locker.notify();
}
});
synchronized(locker){
//create a new thread for each request
Thread thread = new Thread(request);
//start() the thread - not run()
thread.start();
//this thread will block until the MyRequest run method calls resume
locker.wait();
}
} catch (Exception e) {
}
}
}
}
public interface ResumeListener {
public void resume();
}
public class MyRequest implements Runnable{
private ResumeListener resumeListener;
public MyRequest(ServerSocket socket) {
}
public void run() {
// do something
resumeListener.resume(); //notify server to continue accepting next request
}
public void addResumeListener(ResumeListener rl) {
this.resumeListener = rl;
}
}
다른 팁
당신이 사용할 수 있는 java.util.동시에 이루어 집니다.CountDownLatch 으로의 개수 1 니다.하의 인스턴스를 만들고 공유하는 부모와 자식의 스레드(예를 들어,그것을 만들기에 HttpRequest
의 생성자,그리고 그것을 검색하여 회원 기능).서버는 다음 전화 await()
에 그것은,그리고 스레드에 안타 countDown()
일 준비가 되었을 때 릴리스의 부모입니다.
당신은 아마도를 사용해야 Java 상태.에서 docs:
조건(으로도 알려진 조건 큐 또는 변수를 조건)제공 수단에 대한 하나의 스레드를 일시 중단 실행(wait)할 때까지 통보 다른 스레드에 의해 일부 국가 조건은 지금 사실일 수 있습니다.
실행하고 디버거에서 설정 중단점?
는 경우 실현성,다음을 읽는에서 선 시스템입니다.니까?