Dibujé dos clases que heredan de
Runnable
. Tienen un relleno sencillo (Thread.sleep and sout). Estaba investigando la posibilidad de interrumpir subprocesos usando interrupted
y isInterrupted
. Por alguna razón, la interrupción no ocurre, pero la ejecución del programa entra en un bucle y ocurre un error:
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)
Después de que se produce el error, los subprocesos continúan funcionando indefinidamente. Pero si elimina Runnable
la llamada de las clases heredadas de Thread.sleep
, entonces el programa se ejecuta normalmente. ¿Cuál es el problema, por qué ocurre el error y por qué el programa no finaliza? Aquí 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();
}
}
Primer 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");
}
}
}
Segunda clase:
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");
}
}
}
Gracias por tus comentarios sobre el tema)
GO TO FULL VERSION