2017-05-14 485 views
-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()方法 「運行執行」 行打印一次。我不明白哪個是問題,有沒有人可以幫助我? 謝謝!

+1

你會期待多少?它被執行,並且線程陷入無限循環,while(真)不做任何事情。 – Antoniossss

回答

1
System.out.println("run execution"); 
while(true); 

這就是問題所在。爲什麼打印到控制檯之後,你會無限循環?我假設你要執行無限次的打印語句。也許你想做這樣的事情?

while (true) { 
     System.out.println("run execution"); 
} 
相關問題