JavaRush /Java Blog /Random EN /Thread interrupts (interrupte thread)
Pegas
Level 34
Гродно

Thread interrupts (interrupte thread)

Published in the Random EN group
I sketched two classes that inherit from Runnable. They have a simple stuffing (Thread.sleep and sout). I have been looking into the issue of interrupting threads with interruptedand isInterrupted. For some reason, the interrupt does not occur, and the program execution loops and an error occurs: Thread interrupts (interrupte thread) - 1
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.codegym.test.myExample.example.thread.Producer.run(Producer.java:15)
	at java.lang.Thread.run(Thread.java:745)
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.codegym.test.myExample.example.thread.Consumer.run(Consumer.java:15)
	at java.lang.Thread.run(Thread.java:745)
After the error is thrown, threads continue to work indefinitely. But if Runnablethe call is removed from the classes inherited from Thread.sleep, then the program works normally. What is the catch, why does the error occur and why does the program not exit? Here main:
public class Solution
{
    public static void main(String[] args) throws InterruptedException
    {
        Thread thread1 = new Thread(new Producer());
        Thread thread2 = new Thread(new Consumer());

        thread1.start();
        thread2.start();

        Thread.sleep(1500);

        thread1.interrupt();
        thread2.interrupt();
    }
}
First grade:
public class Producer implements Runnable
{
    @Override
    public void run()
    {
        while (!Thread.interrupted())
        {
            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("Producer");
        }
    }
}
Second class:
public class Consumer implements Runnable
{
    @Override
    public void run()
    {
        while (!Thread.interrupted())
        {
            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("Consumer");
        }
    }
}
Thank you for your comments on the topic
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION