Java锁定条件似乎无法正常工作

问题描述 投票:0回答:1

我在有BoundedBuffer且有ConsumersProducers时遇到问题,生产者填充了缓冲区,而使用者从缓冲区中删除了。

我正在为消费者和生产者使用线程,并且我试图使用锁定条件以确保该缓冲区对于生产者而言不是满的,并且对于消费者来说不是空的。

不幸的是,它没有按照我想要的方式工作,似乎消费者/生产者处于状态中。等待他们不让其他线程工作,不应该让他们吗?

这是我的代码


class main
{
    public static void main (String[] args) throws InterruptedException
    {
        final int N = Integer.parseInt(args[0]); 
        BoundedBuffer teste = new BoundedBuffer(N);
        Thread c = new Consumidor(teste,N);
        Thread p = new Produtor(teste,N);
        c.start();
        p.start();
        c.join();
        p.join();
    }
}

class BoundedBuffer
{
    ArrayList<Integer> array;
    int index;
    int size;

    Lock l = new ReentrantLock();
    Condition notFull = l.newCondition();
    Condition notEmpty = l.newCondition();

    BoundedBuffer(int N)
    {
        this.array=new ArrayList<Integer>(N);
        this.index = 0;
        this.size=N;
    }

    public synchronized void put(int e) throws InterruptedException 
    {
        l.lock();
        try
        {
            while(this.index >= this.size)
            {
                notFull.await();
            }
            this.array.add(index,e);
            this.index++;
            notEmpty.signal();
        }
        finally
        {
            l.unlock();
        }       
    }

    public synchronized int get() throws InterruptedException 
    {
        int i;
        l.lock();
        try
        {   
            while(this.index <=0)
            {           
                notEmpty.await();
            }
            this.index--;
            notFull.signal();
            i = this.array.get(index);
        }
        finally
        {
            l.unlock();
        }
         return i;

    }
}

class Consumidor extends Thread
{
    private BoundedBuffer b;
    final int j;
    public Consumidor(BoundedBuffer b, int j)
    {
        this.b = b;
        this.j=j;
    }
    public void run() 
    { 
        int a;
        for (int i = 0; i < j ;++i)
        {  
            try
            {  
                a=b.get();
                System.out.println("GET: " +a); 
            }
            catch (Exception e) {}
        }
    }
}


class Produtor extends Thread
{
    private BoundedBuffer b;
    final int j;
    public Produtor(BoundedBuffer b, int j)
    {
        this.b = b;
        this.j=j;
    }
    public void run() 
    { 
        int a;
        for (int i = 0; i < j; ++i)
        {   
            try
            { 
                b.put(i);
                System.out.println("PUT: " +i);
            }
            catch (Exception e) {}
        }
    }
}

非常感谢

java multithreading conditional-statements locks
1个回答
1
投票

不要将内在锁(意思是同步的)与reentrantLocks混合使用。这段代码试图获取内部锁,然后获取reentrantlock。

从代码中删除synced关键字。同步使用对象上的固有锁定。使用ReentrantLock的代码不需要它,只会造成麻烦。

© www.soinside.com 2019 - 2024. All rights reserved.