Java NiO causes a strange problem that Java server programs cannot be closed

Source: Internet
Author: User

The core code of the server is as follows:

@ Override public void receivedata () throws ioexception {// todo auto-generated method stub recthread = new recthread (); crtthread = new thread (recthread); crtthread. start ();} class recthread implements runnable {public void run () {try {Listen ();} catch (ioexception e) {e. printstacktrace () ;}}// listens to client connections and data public void listen () throws ioexception {system. out. println ("START"); While (threadflag) {If (threa Dflag) {selector. select (); set <selectionkey> selectionkeys = selector. selectedkeys (); iterator = selectionkeys. iterator (); While (iterator. hasnext () {selectionkey = (selectionkey) iterator. next (); handlekey () ;}} if (selectionkey! = NULL) {selectionkey. Cancel ();} selector. Close ();}

Then execute receivedata () to start the thread for listening. When closing the program, you only need to set threadflag to false before closing the program so that the thread can exit automatically.

After testing, I found that if the client and server have established a connection and communicated, you can use the above method to completely close the program,

 

If only the service end starts the listening thread and no client is connected, javaw.exe is still running in the background after the service end is closed. Although the thread running mark threadflag is set to false, it is clear that the thread is still running.

I don't understand it when I am running it. Later I studied it and found that as long as there is selector in the thread code. select (); then this thread cannot be closed, and there is no way to use it.

Runtime rt = Runtime.getRuntime();    String command = "taskkill /F /IM javaw.exe";        try    {      rt.exec(command);      System.out.println("success closed");    }    catch (IOException ex)    {      ex.printStackTrace();    }

 

This stupid method completely closes the program ......

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.