my thread ignore flag interrupt

hi mate i have a simple thread that i want to terminate when flag interrupt is on. this is the code at the begin of run method

conn = false;
for (int i=0; (isInterrupted() == false) && (i < TRY_CONNECT) && !conn; i++) {
    try{
        Log.d(TAG,"TRY"+i);
        sock.connect();
        conn = true;
    } catch (IOException e) {
        try {
            sleep(5000);
        } catch (InterruptedException e1) {
            Log.d(TAG,"CATCH int");
            break;
        }
    }
}
if(isInterruped() == true)
    Log.d(TAG,"INT");

out the thread i call on him interrupt method, and it dont terminate the loop.. he dont see the interrupt that i call... how is possible ? For debug: out where i call interrupt i insert two print with log cat ... thread_reader.interrupt(); boolean b=thread_reader.isInterrupted(); Log.d(TAG,""+b); and on log cat the system print "false" how is possible ? i ve just call interrupt

Answers


When you catch InterruptedException, simply break the loop. Do not rely on isInterrupted() check in the loop header, as the interrupted flag is cleared when the InterruptedException is thrown.


Whenever you catch InterruptedException this clears the interrupt flag on the thread. You need to do something like following pattern as a matter of course every time you do the catch:

try {
     sleep(5000);
} catch (InterruptedException e1) {
     Log.d(TAG,"CATCH int");
     // _always_ re-interrupt the thread since the interrupt flag is cleared
     Thread.currentThread().interrupt();
     // you probably want to break
     break;
}

As @Alexei mentioned, you could put a break or return in the catch block to exit the thread immediately. But either way, you should always re-interrupt the Thread so that other parts of your program can detect that an interrupt condition was set on the Thread.

See this question/answer for more information:

Why would you catch InterruptedException to call Thread.currentThread.interrupt()?


Need Your Help

LocalBroadcastManager and the Activity lifecycle

android android-lifecycle localbroadcastmanager

So I'm looking into the feasibility of changing from callback interfaces to local broadcasts for some long-running network operations. Since the Activity lifecycle creates all sorts of complication...

Unable to bind datepicker to the dynamically added textbox in jquery

jquery asp.net-mvc-4 razor

I have a DIV which will be added dynamically based on my dependents selected.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.