我正在尝试创建一个线程服务器。我使用线程池创建一堆线程来处理来自每个客户端的数据。每个线程都需要从第二台服务器发送和接收信息。我创建了一个类来处理与第二个服务器的连接,包括生成inputObjectStream / OutputObjectStram;每个线程创建一个连接类的新实例,所以我认为流是独立的,无需同步连接类,但是当我不同步流时,不能成功创建。
根据我的理解,每个线程的套接字和流应该是私有的,我错了吗?
这是一个非常简短的伪代码结构,我试图澄清一下。
public static void main(){
//Create the threads
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
for(int i=0; i<X;i++){
Runnable worker = new ProcessCommands(list, GeneratorResponse);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
}
public ProcessCommands(List<String> list, String threadName){
public void run(){
Connection Connect = new Connection();
Connect.getData();
}
}
public class Connection implements Serializable{
private static Socket WG_Socket= null;
private static String WG_addr = "b132.seng.uvic.ca";
private static int WG_Port = 44433;
public Connection(){
}
public int getData(){
WG_Socket = new Socket(WG_addr,WG_Port);
ObjectOutputStream out = new ObjectOutputStream(WG_Socket.getOutputStream());
out.writeObject("Send Data");
ObjectInputStream in = new ObjectInputStream(WG_Socket.getInputStream());
return (Integer)in.readObject();
}
}