safriansah

Proses yang Kooperatif

Jul 22nd, 2018
633
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class BoundedBuffer {
  4.  
  5.   public BoundedBuffer() {
  6.     // buffer diinisialisasikan kosong
  7.     count = 0;
  8.     in    = 0;
  9.     out   = 0;
  10.  
  11.     buffer = new Object[BUFFER_SIZE];
  12.   }
  13.  
  14.   // produser memanggil method ini
  15.   public void enter( Object item ) {
  16.     while ( count == BUFFER_SIZE )
  17.       ; // do nothing
  18.  
  19.     // menambahkan suatu item ke dalam buffer
  20.     ++count;
  21.     buffer[in] = item;
  22.     in = ( in + 1 ) % BUFFER_SIZE;
  23.  
  24.     if ( count == BUFFER_SIZE )
  25.       System.out.println( "Producer Entered " +
  26.         item + " Buffer FULL" );
  27.     else
  28.       System.out.println( "Producer Entered " +
  29.         item + " Buffer Size = " + count );
  30.   }
  31.  
  32. // consumer memanggil method ini  
  33. public Object remove() {
  34.     Object item ;
  35.  
  36.     while ( count == 0 )
  37.       ; // do nothing
  38.    
  39.     // menyingkirkan suatu item dari buffer
  40.     --count;
  41.     item  = buffer[out];
  42.     out   = ( out + 1 ) % BUFFER_SIZE;
  43.  
  44.     if ( count == 0 )
  45.       System.out.println( "Consumer consumed " +
  46.         item + " Buffer EMPTY" );
  47.     else
  48.       System.out.println( "Consumer consumed " +
  49.         item + " Buffer Size = " +count );
  50.  
  51.     return item;
  52.   }
  53.  
  54.   public static final int NAP_TIME = 5;
  55.   private static final int BUFFER_SIZE = 5;
  56.  
  57.   private volatile int count;
  58.   private int in;       // arahkan ke posisi kosong selanjutnya
  59.   private int out;      // arahkan ke posisi penuh selanjutnya
  60.   private Object[] buffer;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment