【发布时间】:2011-06-05 21:15:59
【问题描述】:
我在 java 中有一个应用程序,它正在扮演服务器的角色。为了限制传入连接的数量,我正在使用 ThreadPool 服务器。
但是我在理解部分代码时遇到了一些问题:
这是你的代码:
protected ExecutorService threadPool =
Executors.newFixedThreadPool(5);
public ThreadPooledServer(BlockingQueue queue,int port) {
this.serverPort = port;
this.queue=queue;
}
while (!isStopped()) {
Socket clientSocket = null;
try {
System.out.println("Serverul asteapta clienti spre conectare la port" +serverPort);
clientSocket = serverSocket.accept();
clientconnection++;
System.out.println("Serverul a acceptat clientul cu numarul:"
+ clientconnection);
} catch (IOException e) {
if (isStopped()) {
System.out.println("Server Stopped.");
return;
}
throw new RuntimeException("Error accepting client connection",
e);
}
WorkerRunnable workerRunnable = new WorkerRunnable(queue,clientSocket);
this.threadPool.execute(workerRunnable);
}
this.threadPool.shutdown();
System.out.println("Server Stopped.");
}
private synchronized boolean isStopped() {
return this.isStopped;
}
public synchronized void stop() {
this.isStopped = true;
try {
this.serverSocket.close();
}
catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
private void openServerSocket() {
try {
InetSocketAddress serverAddr = new InetSocketAddress(SERVERIP,
serverPort);
serverSocket = new ServerSocket();
serverSocket.bind(serverAddr);
} catch (IOException e) {
throw new RuntimeException("Cannot open port", e);
}
}
什么我不明白:
我正在使用接受 5 个传入连接的 ThreadPooledServer....
与客户端的连接在 while() 循环中完成。
while (!isStopped()) {
}
isStopped 是此函数返回的布尔变量:
private synchronized boolean isStopped() {
return this.isStopped;
}
我称之为启动循环的条件。
这个布尔变量最初设置为false.....然后在这里设置回true:
public synchronized void stop() {
this.isStopped = true;
}
什么时候设置回真我的 while() 循环结束,然后我关闭我的线程池的所有工作人员。
this.threadPool.shutdown();
问题是我从不调用这个函数“stop()”
问题:当我关闭服务器时,该函数是否会自动调用??????...或者我应该在某个地方调用它????
【问题讨论】: