Java中线程失败的常见原因是什么

时间:2019-02-09 07:23:41

标签: java

我们有一个Java 8应用程序,它的打印机线程失败/没有间歇响应,我只是想知道线程失败的最常见原因是什么,我的理解是不能对线程进行垃圾回收,因此可以排除在外,我们可以使用LinkedList添加remove和isEmpty来锁定线程。线程的内存不足,只有在不影响主线程或其他线程时才可能发生。而且OutOfMemory Heap不太可能,因为它将影响整个程序。失败/挂起的线程基本上是一个工作线程,它通过调用printSystemthreads方法添加到LinkedList中,从而将其添加到LinkedList中,然后通知正在等待从链表中读取的相同线程run方法。

 // This method is called by a Worker Thread to add a print message.
 printAdd(object message) {
    synchronized(this)
    { 
      printList.add(message);
      try {
      this.notifty();
      }
      catch(Exception e){} 
   } 
 }

 run() {

 while(true)
   synchronized(this)
     try{
     this.wait();
      while(!printList.isEmpty()) {
             message = printList.remove();
             // Code not show but determines the message type
             // And then sends to the correct printer  


      }
     }
     catch(Exception e){}
   }            

   }
}

1 个答案:

答案 0 :(得分:0)

作为user207421提及线程失败与任何失败的常见原因相同,此外,由于线程正在处理被锁定的共享变量,线程也可能由于线程死锁而挂起。我认为在上面的示例中,未同步printList.isEmpty()可能是问题所在。一种解决方案可能是将非ThreadSafe的LinkedList移至BlockingQueue接口之类的线程安全替代方案。