Search code examples
javamultithreadingsleepinterrupted-exceptioninterruption

Thread - Sleep and interrupt


Please first see this snippet:

public static void main(String[] args) throws InterruptedException {
    Thread anotherThread = new Thread(() -> {
        Integer countB = 0;
        while (true) {
            try {
                System.out.println("B count: " + ++countB);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    anotherThread.start();

    Integer countA = 0;
    while (true) {
        System.out.println("A count: " + ++countA);
        Thread.sleep(1000);
    }
}

This works as expected. I see countA to be approximately 2x of countB.

Now I add one line to the outer while loop:

public static void main(String[] args) throws InterruptedException {
    Thread anotherThread = new Thread(() -> {
        Integer countB = 0;
        while (true) {
            try {
                System.out.println("B count: " + ++countB);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    anotherThread.start();

    Integer countA = 0;
    while (true) {
        anotherThread.interrupt();
        System.out.println("A count: " + ++countA);
        Thread.sleep(1000);
    }
}

Main thread interrupts anotherThread. After I do this, countA is no longer 2x countB. They always differ by one now.

Why so? How does sleep/interrupt work?


Solution

  • This is an addition to Buddy's answer, which is correct.

    In first case you have

    B    A
    .    .
    .    A
    .    .
    B    A
    .    .
    .    A
    .    .
    B    A
    

    but with interrupt it changed to:

    B    A (interrupts B, B continues in loop)
    B    .
    .    A (interrupts B again)
    B    .
    .    A
    B    .
    .    A
    B    .
    .    A
    

    causing B not to wait 2 seconds...