Why Some Thread.sleep() Are Not Interrupted?

Write here if you have problems with your Java source code

Moderator: Board moderators

Post Reply
User avatar
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Why Some Thread.sleep() Are Not Interrupted?

Post by ImLazy » Wed May 04, 2011 3:48 am

First, see this code.
Very simple, there are 20000 threads, named thread1~thread10000 and thread1-sleep~thread10000-sleep.
Every threadi-sleep sleeps for 1 second and threadi interrupts it:

Code: Select all

public class InterruptTest {
    
    public static void main(String[] args) throws Exception {
        for (int i = 1; i <= 10000; i++) {
            Thread t = new Interrupt();
            t.setName("thread" + i);
            t.start();
        }
    }
    
    private static class Interrupt extends Thread {
        public void run() {
            Thread t = new Sleep();
            t.setName( getName() + "-sleep" );
            t.start();
            t.interrupt();
            System.out.println( System.currentTimeMillis() + " " +
                                t.getName() + " " + t.isInterrupted() );
        }
    }
    
    private static class Sleep extends Thread {
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                return;
            }
            System.err.println( System.currentTimeMillis() + " No! " +
                                getName() + " " + isInterrupted() );
        }
    }
    
}
I supposed the last System.err.println() should never be executed, because the Thread.sleep() must be interrupted and it should go to the return. But the program did output to stderr:

Code: Select all

1304393164531 No! thread949-sleep true
1304393164562 No! thread1128-sleep false
It doesn't output every time, looks it happens occasionally.
As you can see, I let it output a line after every interrupt() statement. And I found 2 lines of output in stdout, I put them together:

Code: Select all

1304393163531 thread949-sleep true
1304393164531 No! thread949-sleep true
1304393163562 thread1128-sleep true
1304393164562 No! thread1128-sleep false
See, I'm sure the 2 interrupt() statements have been executed, 1 second before the stderr output. So why weren't they interrupted?

P.S. I have tried 3 computers, they are all Windows XP. And this situation happened on 2 of them, which are Core 2 Duo 2.4GHz. And it didn't happend on another PC, which is Celeron 1.5GHz! Their JDK are the same, version 1.6.
I stay home. Don't call me out.

Post Reply

Return to “Java”