簡體   English   中英

Java並發中的條件vs信號量

[英]Condition vs Semaphore in java concurrency

我無法解決作業問題。 這個問題要求我們僅通過將Semaphore用作並發控制類來模仿Condition的實現,而別無其他。 有人可以通過解釋問題的確切含義來指出我的方向嗎

在示例MySemaphore.java中,我們使用Lock和Condition實現了一個Semaphore。 現在,仍然保持相同的精神,實現一個類MyCondition,該類的工作方式類似於Condition,帶有方法wait和signal(無需在此處實現其余方法)。 在您的實現中,唯一允許使用的並發控制類是Semaphore。

這是問題中提到的例子

import java.util.concurrent.locks.*;

// A standard exercise of Concurrency 101 is to show that Semaphores are
// equivalent to Locks and Condition Variables in power, by implementing
// one with the other. Here, a simple Semaphore implementation.

public class MySemaphore {
    private int permits;
    private Lock mutex;
    private Condition permitAvailable;

    public MySemaphore(int permits, boolean fair) {
        this.permits = permits;
        this.mutex = new ReentrantLock(fair);
        this.permitAvailable = mutex.newCondition();
    }

    public void acquire() throws InterruptedException {
        mutex.lock();
        try {
            while(permits < 1) {
                // Wait for one permit to become available.
                permitAvailable.await();
            }
            permits--;
        }
        // Ensure that mutex is unlocked even if an exception is thrown.
        finally { mutex.unlock(); }
    }

    public void release() {
        mutex.lock();
        permits++;
        // One waiting thread can now acquire a permit.
        permitAvailable.signal();
        mutex.unlock();
    }
}

如果這是您的家庭作業,請首先檢查j2se的Lock&Condition&Semaphore的源代碼。 然后嘗試實施它,以使您的作業有意義,它使您了解機制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM