Friday, 15 May 2015

eclipse - How to destroy a thread in Java -



eclipse - How to destroy a thread in Java -

i'm writing client/server application in java using sockets. in server, have thread accepts client connections, thread runs indefinitely. @ point in application, want stop accepting client connection, guess destroying thread way. can tell me how destroy thread?

here's code:

class clientconnectionthread implements runnable { @override public void run() { seek { // set server hear @ port 2901 server = new serversocket(2901); // maintain on running , take client connections while(true) { // wait client connect socket client = server.accept(); addclient(client.getinetaddress().gethostname(), client); // start new client reader thread socket new thread(new clientreaderthread(client)).start(); } } grab (ioexception e) { showerror("could not set server on port 2901. application terminate now."); system.exit(0); } } }

as can see, have infinite loop while(true) in there, thread never stop unless somehow stop it.

the right way close server socket. cause accept() throw ioexception can handle , quit thread.

i'd add together public void stop() method , create socket field in class.

private serversocket serversocket; public clientconnectionthread() { this.serversocket = new serversocket(2901); } ... public void stop() { serversocket.close(); } public void run() { while(true) { // throw when socket closed stop() method socket client = server.accept(); ... } }

java eclipse multithreading sockets runnable

No comments:

Post a Comment