我畫了兩個繼承自 的類別
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