您的位置:首页 > 理论基础 > 计算机网络

改造-TCP-Java-客户机/服务器应用程序-并发-限制线程上限

2015-03-23 13:11 323 查看
原代码

改造后的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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐