Pawan
Pawan

Reputation: 32331

Why is that Thread interupt method is not breaking its sleep method?

I have this program below

package com;
public class ThreadDemo implements Runnable {
    @Override
    public void run() {
        while(true)
        {
            try {
                System.out.println("Into sleep");
                Thread.sleep(1000000000);
                System.out.println("Out of sleep");
                } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public static void main(String args[]) {
        ThreadDemo tD = new ThreadDemo();
        Thread t1 = new Thread(tD);
        t1.start();
        t1.interrupt();
    }
}

I have started the Thread , and will call its run method and goes into sleep state for the above specified seconds .

i have called t1.interrupt();

This is the screen shot

enter image description here

My question is that why

1.The Thread is not coming out of sleep state ?

  1. Why Into sleep is printed twice ??

Upvotes: 1

Views: 75

Answers (2)

Logman
Logman

Reputation: 4189

1.The Thread is not comng out of sleep state ?

He actually is but

System.out.println("Out of sleep");

is never executed because when you interrupt Thread.sleep(10000); throws a exception and

e.printStackTrace();

is execute instead

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502086

You're in a loop:

  • You're sleeping
  • Being interrupted and printing the stack trace
  • Going back to sleep
  • Never being interrupted again

So it is "coming out of sleep state" (otherwise you wouldn't see the stack trace) - but you're then calling Thread.sleep again.

If you only want to sleep once, get rid of the loop...

Upvotes: 4

Related Questions