Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Mar 20, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

What is the Thread.interrupt()method's purpose?

What is the purpose of the Thread.interrupt() method? I expect that if I call the interrupt() method of a sleeping thread, an InterruptedException will be thrown. Here is a quick code sample showing my thoughts (please forgive the formatting):

   class Timer extends Thread {
      public void run() {
               for(int i = 0; i < 20; i++) {
                  try {
                         catch (InterruptedException e) {

   public class Scheduler {
       public Scheduler() {
                      timer_ = new Timer();

            public void foo() {

            private Timer timer_;

      public static void main(String args[]) {
         Scheduler s = new Scheduler();

I expect that when s.foo() is called, I will see output resembling
What am I missing?

I compiled and ran this code, and no message appeared. The curious behavior you're experiencing can probably be attributed to the fact that like an Error, an InterruptedException is asynchronous. In other words, the InterruptedException is thrown at a slightly different point during the execution of _timer each time it runs.

Asynchronous exceptions aren't handled the same way as other exceptions. The Java virtual machine must periodically check to see if any asynchronous exceptions have been raised. This is usually done by special instructions inserted into your code by the compiler. Naturally, this raises code optimization issues. Some compilers only insert checks for asynchronous exceptions after a "transfer of control." This may mean a function call or a context switch. It might even be the case that some compilers have an optimization option that doesn't insert any checks for these exceptions.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date