Check if a thread is interrupted?

I just want to get know about if this thread is interrupting or not if I'm doing it right? please give me hint if I'm wrong

public void run(){
  int i;
  while(!Thread.currentThread().isInterrupted()){
    for(i=1;i<=100;i++){

      System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);

      if(i==3){
        Thread.currentThread().interrupt();
        gotoInform();
        break;
      }
      try{
        Thread.currentThread().sleep(1000);////to sleep the Thread for 1 Second (1000ms)
      }
      catch(Exception e){            
        System.out.printf("Error"+e);            
      }
    }
  }

Answers


This is wrong, because if sleep finds that the thread is interrupted, it will throw an InterruptedException and clear the interrupted flag. You then swallow that exception, suppressing any record that the thread was ever interrupted. Instead, you should write something more like this:

public void run(){
    for(int i=1;i<=100;i++){

        System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);

        if(i==3){
            Thread.currentThread().interrupt();
            gotoInform();
            break;
        }
        try{
            Thread.currentThread().sleep(1000);
        }
        catch(final Exception e){
            e.printStackTrace();
            if(e instanceof InterruptedException) {
                // just in case this Runnable is actually called directly,
                // rather than in a new thread, don't want to swallow the
                // flag:
                Thread.currentThread().interrupt();
            }
            return;
        }
    }
}

(Note: I'm assuming that this is not "real" code, but rather, that you're just trying to learn how thread interruption works. In "real" code, you should almost never need to interrupt the current thread in this way.)


Need Your Help

How do you alternate Ninject bindings based on user?

c# asp.net-mvc asp.net-mvc-3 dependency-injection ninject

This question requires a bit of context before it makes sense so I'll just start with a description of the project.

Is there a restriction on using a BitmapImage (or other UI namespace classes) on a none- UI thread?

c# windows-store-apps

I'm doing some cloud operations involving a BitmapImage in my code, and on the response (basically a none-UI thread for sure) I'm getting a "The application called an interface that was marshalled ...

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.