views:

135

answers:

2

While Going through the java tutorial on sun site, I see following piece of code:

for (int i = 0; i < inputs.length; i++) {
    heavyCrunch(inputs[i]);
    if (Thread.interrupted()) {
        //We've been interrupted: no more crunching.
        return;
    }
}

Since Thread.interrupted() is a static function, how does java knows which thread is calling it? eg. I expected it to be of type: this.interrupted() or Thread.interrupted(this).

A: 

Thread.interrupted() will execute in the same thread as your loop, so that method will simply check whether the current thread has been interrupted.

Sander
not clear, since this flag instance variable how can a static function check it?
sachin
+3  A: 

It looks at Thread.currentThread().


If you want to know how that works, it's a native method, and probably JVM-specific so there's no quick answer.

Robert Munteanu
Same question applies to this function call as well, since there can be multiple threads running at the same time on a multicore machine, how can jvm determine current thread?
sachin
See my update - the method is native and probably hooks straight into the JVM - it's not 'java' code anymore.
Robert Munteanu
@sachinThe current thread is defined as the thread that actually called interrupted(). How many other threads are running and on which core is irrelevant.
Tal Pressman