لقد رسمت فئتين ترثان من
Runnable
. لديهم حشوة بسيطة (Thread.sleep وsout). كنت أبحث في مقاطعة المواضيع باستخدام interrupted
و isInterrupted
. لسبب ما، لا يحدث الانقطاع، ولكن تنفيذ البرنامج يدخل في حلقة ويحدث خطأ:
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)
بعد حدوث الخطأ، تستمر مؤشرات الترابط في العمل إلى أجل غير مسمى. ولكن إذا قمت بإزالة Runnable
الاستدعاء من الفئات الموروثة من Thread.sleep
، فسيعمل البرنامج بشكل طبيعي. ما هي المشكلة ولماذا يحدث الخطأ ولماذا لا ينتهي البرنامج؟ هنا 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();
}
}
الصف الاول:
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");
}
}
}
الصف الثاني:
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");
}
}
}
شكرا لتعليقاتك على الموضوع)
GO TO FULL VERSION