JavaRush /Java Blog /Random EN /Interrupte thread
Pegas
Level 34
Гродно

Interrupte thread

Published in the Random EN group
I sketched two classes that inherit from Runnable. They have a simple filling (Thread.sleep and sout). I was looking into interrupting threads using interruptedand isInterrupted. For some reason, the interruption does not occur, but the program execution goes into a loop and an error occurs: Interrupte thread - 1
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.javarush.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.javarush.test.myExample.example.thread.Consumer.run(Consumer.java:15)
	at java.lang.Thread.run(Thread.java:745)
After the error occurs, the threads continue working indefinitely. But if you remove Runnablethe call from the classes inherited from Thread.sleep, then the program runs normally. What is the problem, why does the error occur and why does the program not terminate? 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");
        }
    }
}
Thanks for your comments on the topic)
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION