I sketched two classes that inherit from
Runnable
. They have a simple filling (Thread.sleep and sout). I was looking into interrupting threads using interrupted
and isInterrupted
. For some reason, the interruption does not occur, but the program execution goes into a loop and an error occurs:
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 Runnable
the 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)
GO TO FULL VERSION