Ho abbozzato due classi che ereditano da
Runnable
. Hanno un riempimento semplice (Thread.sleep e sout). Stavo cercando di interrompere i thread utilizzando interrupted
e isInterrupted
. Per qualche motivo, l'interruzione non si verifica, ma l'esecuzione del programma entra in un ciclo e si verifica un errore:
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)
Dopo che si è verificato l'errore, i thread continuano a funzionare all'infinito. Ma se rimuovi Runnable
la chiamata dalle classi ereditate da Thread.sleep
, il programma verrà eseguito normalmente. Qual è il problema, perché si verifica l'errore e perché il programma non si chiude? Qui 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();
}
}
Primo grado:
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");
}
}
}
Seconda 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");
}
}
}
Grazie per i tuoi commenti sull'argomento)
GO TO FULL VERSION