2017-05-14 488 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"); 
} 
相关问题