J'ai esquissé deux classes qui héritent de
Runnable
. Ils ont un remplissage simple (Thread.sleep et sout). Je cherchais à interrompre les threads en utilisant interrupted
et isInterrupted
. Pour une raison quelconque, l'interruption ne se produit pas, mais l'exécution du programme entre en boucle et une erreur se produit :
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)
Une fois l’erreur survenue, les threads continuent de fonctionner indéfiniment. Mais si vous supprimez Runnable
l'appel des classes héritées de Thread.sleep
, alors le programme s'exécute normalement. Quel est le problème, pourquoi l’erreur se produit-elle et pourquoi le programme ne se termine-t-il pas ? Ici 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();
}
}
Première année:
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");
}
}
}
Seconde 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");
}
}
}
Merci pour vos commentaires sur le sujet)
GO TO FULL VERSION