看了很多网上的例子,都是启动相关线程就ok了。至于如何关闭相关线程,却没有这方面资料。
举例说明:以消费者为例public void run(){
   while(status){
      //访问队列
      队列.getElement();
   }
}队列:
public Object getElement(){
    if(isEmpty()){
       this.wait();
    }   //获取队列元素
}上面是两个示例代码。status是一个布尔值,标识消费者线程的结束标志。如果为false,则线程结束。可能存在这样的情况,当判断完status为true时,此时消费者线程要访问队列,而这时status被设置为false。这就意味着消费者线程不会马上结束,还会调用队列的getElement()方法去获取元素。但是如果生产者线程已经停止,队列为空,则isEmpty()为true,此时消费者线程就会一直wait,导致该线程永远不会结束。因为此时的生产者线程已经over了,不会再有别的线程调用notify()来唤醒消费者线程。不知道大家如何解决这个问题。

解决方案 »

  1.   

    1.public static void yield()
    Causes the currently executing thread object to temporarily pause and allow other threads to execute. 2.public final void wait()throws InterruptedException
    Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0). 
    The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution. As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:      synchronized (obj) {
             while (<condition does not hold>)
                 obj.wait();
             ... // Perform action appropriate to condition
         }
     
    This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor. Throws: 
    IllegalMonitorStateException - if the current thread is not the owner of the object's monitor. 
    InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
    See Also:
    notify(), notifyAll()
      

  2.   

    是这个不?
    http://blog.csdn.net/KingWolfOfSky/archive/2010/04/08/5464990.aspx
      

  3.   

    存在这种情况。那么你就把判断status和getElement做成事务性的操作。楼主贴出代码供分析比较好。