java thread pool exectur执行一次

时间:2017-05-14 15:28:07

标签: java

我正在尝试编写分布式多人游戏。该体系结构是一个经典的服务器客户端,它使用套接字进行通信。我想在服务器中创建一个线程池,以通过相应的套接字将每个客户端匹配到不同的线程。问题是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();
    }
  }
}

Runnable执行:

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);
  }
}

问题是该行&#34;运行执行&#34;在run()方法中打印一次。我不明白哪个是问题,有没有人可以帮助我? 谢谢你!

1 个答案:

答案 0 :(得分:1)

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

这就是问题所在。为什么在打印到Console后,你会进入无限循环?我假设你想无限次地执行print语句。可能你想做这样的事情吗?

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