2015-11-13 66 views
-1

在研究如何使用同步缓冲区时,我需要使用缓冲区接口才能完成分配。我很确定我的整个代码是正确的,除了我如何实现缓冲区。我在公开课上得到了一个错误代码,说“接口在这里”。提示告诉我要扩展Buffer而不是实现它。有没有人有任何想法,我缺少什么? (这是四类中的一类)。如何正确实现Java的Buffer接口?

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); 
    } 
} 

编辑::我editted的代码去除进口java.nio.Buffer中;

+1

Eh? 'java.nio.Buffer'是一个类,而不是一个接口。你为什么认为你需要自己写? – EJP

+1

@EJP而'Buffer'构造函数是包私有的,所以你**不能**实现你自己的。 OP必须误解家庭作业的某些部分。 – Andreas

+0

我觉得我是。我使用了Java.nio.Buffer;因为IDE暗示这是我需要修复原始错误。我原来得到了错误“找不到符号符号:类缓冲区缺少javadoc” 我添加了java.nio.Buffer并得到了我上面解释的错误。 – Cigaro

回答

0

我现在明白了这个问题。上次我实现一个接口时,接口本身已经从另一个文件导入。我不知道我需要实际写出接口。我想这可能已被列入像列表,集合,地图等Java框架...

Anywho我需要创建一个Buffer.java:

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

    public int get() throws InterruptedException; } 

@EJP和安德烈斯。感谢您发表评论。