-3
我正在嘗試編寫一個分佈式多人遊戲。該體系結構是一個經典的服務器端客戶端,它使用套接字進行通信。我想在服務器中創建一個線程池,通過相應的套接字將每個客戶端匹配到不同的線程。問題是execute(Runnable)方法只能使用一次!這是一段代碼:java線程池exectur執行execute(runnable)方法一次
服務器:
public class Server extends ThreadPoolExecutor{
Server() throws IOException{
super(MIN_POOL_SIZE, MAX_POOL_SIZE, TIME_ALIVE, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(MAX_POOL_SIZE));
listener=new ServerSocket(PORT_NO);
listener.setSoTimeout(SERVER_TIMEOUT);
clients=new ArrayList<ClientConnection>();
System.out.println("Listening on port "+PORT_NO);
}
void runServer(){
Socket socket;
ClientConnection connection;
try{
while(true){
socket=listener.accept();
System.out.println("client accettato");
connection=new ClientConnection(socket, this);
System.out.println("creata la connection");
try{
execute(connection);
//clients.add(connection);
// System.out.println("Accepted connection");
// connection.send("Welcome!");
}
catch(RejectedExecutionException e){
//connection.send("Server is full!!!");
socket.close();
}
}
}
catch (IOException ioe){
try{listener.close();}catch (IOException e){
e.printStackTrace();
}
System.out.println("Time to join the match expired");
//init();
}
}
}
可運行以執行:
public class ClientConnection extends Player implements Runnable{
// private static final boolean BLACK=false;
// private static final boolean WHITE=true;
// private int ammo;
// private boolean team;
private volatile BufferedReader br;
private volatile PrintWriter pw;
private volatile Server server;
private volatile Socket socket;
public ClientConnection(Socket s, Server srv) throws IOException{
super(10+(int)Math.random()*30, true);
socket=s;
server=srv;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
System.out.println("costruzione nuovo socket");
}
@Override
public void run(){
System.out.println("run execution");
while(true);
}
public void send(String message){
pw.println(message);
}
}
的問題是,在run()方法 「運行執行」 行打印一次。我不明白哪個是問題,有沒有人可以幫助我? 謝謝!
你會期待多少?它被執行,並且線程陷入無限循環,while(真)不做任何事情。 – Antoniossss