2009-05-11 2 views
0

우리는 우리가했던 그 클래스 에서 세마포어를 사용하고 싶지만 취득()의 모든 사용에 오류가 있습니다 오류는 다음과 같습니다.내가 소비자와 생산자의 BoundedBuffer 클래스 일하고

보고되지 않은 예외 java.lang.InterruptedException; 잡은 또는 여기

를 슬로우 선언해야하는 코드입니다 :

import java.util.concurrent.Semaphore; 

public class BoundedBuffer implements Buffer { 
    private static final int BUFFER_SIZE = 4; 

    /** 
    * volatile does not appear in the printed text. A discussion of 
    * volatile is in chapter 7. 
    */ 
    private volatile int count; 
    private Object[] buffer; 
    private int in; // points to the next free position in the buffer 
    private int out; // points to the next full position in the buffer 

    private Semaphore mutex; 
    private Semaphore empty; 
    private Semaphore full; 

    public BoundedBuffer() { //constractur 
     // buffer is initially empty 
     //count = 0; 
     in = 0; 
     out = 0; 

     buffer = new Object[BUFFER_SIZE]; 

     mutex = new Semaphore(1); 
     empty = new Semaphore(BUFFER_SIZE); 
     full = new Semaphore(0); 
    } 

    // producer calls this method 
    public void insert(Object item) { 
     //while (count == BUFFER_SIZE) 
     // ; // do nothing the brach full 

     // add an item to the buffer 
     // ++count; 

     empty.acquire(); 
     mutex.acquire(); 
     buffer[in] = item; 
     in = (in + 1) % BUFFER_SIZE;//that to do cyrcle or to go to the begining againe 
/* 
     if (count == BUFFER_SIZE) 
      System.out.println("Baker put " + item + " Shelf FULL"); 
     else 
      System.out.println("Baker put " + item + " Shelf Size = " + count); 
*/ 


     mutex.release(); 
     full.release(); 

    } 

    // consumer calls this method 
    public Object remove() { 
     //Object item; 
     full.acquire(); 
     mutex.acquire(); 

     //while (count == 0) 
      ; // do nothing the buffer is empty 

     // remove an item from the buffer 
     //--count; 

     Object item = buffer[out]; 
     out = (out + 1) % BUFFER_SIZE; 
     mutex.release(); 
     empty.release(); 
     return item; 
    } 
} 

답변

2

어쩌면 내가 완전히 응용 프로그램을 이해하지 않지만, 당신은 이미에서 제공되는 제한된 버퍼 클래스를 사용할 수없는 java.util.concurrent 패키지 (ArrayBlockingQueue)?

이 고전은 고정 된 크기 어레이가 소비자에 의해 추출 된 생산자 삽입 요소를 보유 에서 "버퍼 바운드"이다. 일단 생성되면 용량을 늘릴 수 없습니다. 전체 큐에 요소를 넣으려고하면 넣기 작업은 이됩니다. 빈 큐에서 요소를 검색하려고하면 마찬가지로 블록 이됩니다.

1

오류는 사용자에게 알아야하는 모든 정보를 제공합니다. InterruptedException은 acquire에 의해 thropwn 될 수 있습니다. 따라서 a) catch하고 처리하거나 b) 호출 함수에서 전파 할 수 있어야합니다. 함수에 추가하면 함수가 sepcification을 throw합니다.

관련 문제