میں نے دو کلاسوں کا خاکہ بنایا جو وراثت میں ہیں
Runnable
۔ ان میں ایک سادہ فلنگ ہے (تھریڈ سلیپ اور سوٹ)۔ میں 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