|
|||||
|
|
#1 |
|
|
Can anyone think of a better way to do this? I have a server thread that waits for an incoming connection request. If the user wants to stop 'listening' then they call a method that sets active to false and calls serverSocket.close(). This causes a SocketException which stops the run() method from listening and then we just loop and sleep. The problem is that looping and sleeping is wasted CPU time ... it'd be nice if I could just sleep until the user wants to listen again - I don't want to keep creating and destroying threads since that is resource intensive ... is there a good way to do this? public void run() { while (true) { try { if (active) connected(serverSocket.accept()); else Thread.sleep(500); } catch (InterruptedException e) { /* Continue */ } catch (SocketException e) { /* Socket was closed */ } catch (IOException e) { e.printStackTrace(); } } } |
|
|
#2 |
|
|
> The problem is > that looping and sleeping is wasted CPU time ... it'd be nice if I could > just sleep until the user wants to listen again - I don't want to keep > creating and destroying threads since that is resource intensive ... is > there a good way to do this? Object.wait() and Object.notifyAll() are the tools for this job. Quite possibly someone will post more detailed example code; if not (and it you need it), then do ask more. -- chris |