Esbocei duas classes que herdam de
Runnable
. Têm um recheio simples (Thread.sleep e sout). Eu estava pensando em interromper threads usando interrupted
e isInterrupted
. Por algum motivo, a interrupção não ocorre, mas a execução do programa entra em loop e ocorre um erro:
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)
Após a ocorrência do erro, os threads continuam funcionando indefinidamente. Mas se você remover Runnable
a chamada das classes herdadas de Thread.sleep
, o programa será executado normalmente. Qual é o problema, por que ocorre o erro e por que o programa não termina? Aqui 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();
}
}
Primeira série:
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");
}
}
}
Segunda classe:
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");
}
}
}
Obrigado por seus comentários sobre o assunto)
GO TO FULL VERSION