簡體   English   中英

如何正確實現 Java 的 Buffer 接口?

[英]How do I properly implement the Buffer interface for Java?

在研究如何使用同步緩沖區時,我需要使用 Buffer 接口來完成分配。 除了我如何實現緩沖區之外,我很確定我的整個代碼都是正確的。 我在公共課上收到一個錯誤代碼,上面寫着“此處需要接口”。 提示告訴我要擴展 Buffer 而不是實現它。 有沒有人對我缺少的東西有任何想法? (這是 4 個類中的 1 個)。

package synchronizedbuffer;

public class SynchronizedBuffer implements Buffer {


private int buffer = -1;
private boolean occupied = false;

public synchronized void put(int value) throws InterruptedException {

    while(occupied) {
        System.out.println("Producer tries to write.");
        displayState("Buffer full. Producer waits");
        wait();
    }

    buffer = value;
    occupied = true;
    displayState("Producer writes " + buffer);
    notifyAll();

}

public synchronized int get() throws InterruptedException { 

    while(!occupied) {
        System.out.println("Consumer tries to read");
        displayState("Buffer empty. Consumer waits");
        wait();
    }

    occupied = false;
    displayState("Consumer reads" + buffer);
    notifyAll();
    return buffer;
}

private synchronized void displayState(String operation) {
    System.out.printf("%-40s%d\t\t%b%n%n", operation, buffer, occupied);
    }  
}

編輯:我編輯了代碼以刪除導入 java.nio.Buffer;

我現在明白這個問題了。 上次我實現一個接口時,接口本身是從另一個文件中導入的。 我不知道我需要實際寫出接口。 我認為它可能已包含在 Java 框架中,例如 Lists、Sets、Maps 等......

我需要創建 Buffer.java 的任何人:

public interface Buffer {
    public void put(int value) throws InterruptedException;

    public int get() throws InterruptedException; }

@EJP 和安德烈斯。 感謝您發表評論。

暫無
暫無

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

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