Java阻止列表实现

Dan*_*ber 7 java list blocking

我在SO和Google上搜索了这个问题的答案,但到目前为止找不到合适的解决方案.

我目前正在处理图形路由问题中的LayerManager.经理负责提供和重置固定的图层集.

我想用阻塞列表实现Consumer-Producer模式,以便在没有可用的自由层的情况下阻止传入路由请求.到目前为止,我只发现了阻塞队列,但由于我们不需要FIFO,LIFO但随机访问队列并不真正起作用.为了更精确一点,这样的事情应该是可能的:

/* this should be blocking until a layer becomes available */
public Layer getLayer(){ 

    for ( Layer layer : layers ) {
        if ( layer.isUnused() && layer.matches(request) )
            return layers.pop(layer);
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这个目标?

小智 0

您正在寻找的称为“信号量”。

  1. 创建信号量类
  2. 将其作为字段添加到 Layer 类中

例子

 public class Semaphore 
{
    private boolean signal = false;

    public synchronized boolean take() 
    {
       if(this.signal==true)
            return false;  //already in use
       this.signal = true;
       this.notify();
       return true;
    }

     public synchronized void release() throws InterruptedException
     {
        while(!this.signal) wait();
        this.signal = false;
     }


     public boolean isUnused()
     {
         return !signal ;
     }

}


//2.
class Layer
{
    Semaphore sem =null;

    /*your code*/
     /*sem = new Semaphore(); in constructors*/
    public boolean take()
    {
        return this.sem.take();
    }

    public void release()
    {
        this.sem.release();
    }

    public Layer getLayer()
    { 

        for ( Layer layer : layers ) 
        {
         if ( layer.matches(request) && layer.take())
             return layer;
        }

         return null;
    }
}
Run Code Online (Sandbox Code Playgroud)


同步方法处理访问并发

3. 循环 getLayer 直到

Layer l=null;
while(l==null)
{
    l= getlayer();
    Thread.sleep(100); //set time
}
 // continue
 // do not forget to release the layer when you are done
Run Code Online (Sandbox Code Playgroud)