改造后的Server:
重点是通过Executors.newFixedThreadPool来限制线程上限.此时上限为2
import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server implements Runnable{
Socket connectionSocket;
static int count = 0;
public Server(Socket connectionSocket){
System.out.println(++count);
this.connectionSocket = connectionSocket;
}
public static void main(String argv[]) throws IOException {
ServerSocket welcomeSocket = new ServerSocket(6789);
ExecutorService exec = Executors.newFixedThreadPool(2);
while(true){
Socket connectionSocket = welcomeSocket.accept();
exec.execute(new Server(connectionSocket));
}
}
@Override
public void run() {
String clientSentence = null;
String capitalizedSentence;
BufferedReader inFromClient = null;
try {
inFromClient = new BufferedReader(
new InputStreamReader(
this.connectionSocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataOutputStream outToClient = null;
try {
outToClient = new DataOutputStream(
this.connectionSocket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
clientSentence = inFromClient.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
capitalizedSentence = clientSentence.toUpperCase() + '\n';
try {
outToClient.writeBytes(capitalizedSentence);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
--count;
}
}