Naszkicowałem dwie klasy, które dziedziczą z
Runnable
. Posiadają proste wypełnienie (Thread.sleep i sout). Zastanawiałem się nad przerywaniem wątków za pomocą interrupted
i isInterrupted
. Z jakiegoś powodu przerwanie nie następuje, ale wykonanie programu przechodzi w pętlę i pojawia się błąd:
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)
Po wystąpieniu błędu wątki kontynuują pracę w nieskończoność. Ale jeśli usuniesz Runnable
wywołanie z klas odziedziczonych z Thread.sleep
, program będzie działał normalnie. Na czym polega problem, dlaczego pojawia się błąd i dlaczego program się nie kończy? Tutaj 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();
}
}
Pierwsza klasa:
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");
}
}
}
Druga klasa:
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");
}
}
}
Dziękuję za uwagi w temacie)
GO TO FULL VERSION