public void run() { producer.getReady(); MyBlockingQueue<Integer> buffer = producer.getBuffer(); Integer item = buffer.take(); while (item != null) { System.out.println(this + " fetches " + item + "."); Thread.yield(); item = buffer.take(); } }
public static void main(String[] args) throws InterruptedException { final int NUM = 10; Producer producer = new Producer(10); Consumer[] consumers = new Consumer[NUM]; for (int i = 0; i < NUM; i++) { consumers[i] = new Consumer(producer); } System.out.println("\t== START =="); producer.start(); for (int i = 0; i < NUM; i++) { consumers[i].join(); } System.out.println("\t== OVER =="); }
/** * Create a fat pipe using the threads from the parent * * @param producer the producer * @param pool the group of pipes to add to */ public PooledFatPipe(Producer<T, S> producer, Pool pool, ExceptionListener listener) { this.producer = producer; this.listener = listener; this.pool = pool; name = producer.getClass().getSimpleName(); lock = new Semaphore(0); }
/** * Look for data from all the inputs * * @return true if data was consumed */ private boolean poll(Signal signal, Signal parent) { AtomicReferenceArray<T> o = outputs; for (int i = 0; i < o.length(); i++) { T input = o.getAndSet(i, null); if (input == null) continue; long seq = ++sequence; if (parent != null) parent.signal(); S product = producer.execute(input, reuseReceptors.get(i), signal); signal.signal(); if (!consume(product, seq, 0)) { Thread.yield(); if (!consume(product, seq, 0)) logger.info( "failed to consume product (" + product + ") from producer (" + producer + ")"); } producer.complete(product); return product != null; } return false; }
/** * Create fat pipe using several threads * * @param producer the producer * @param poolSize the size of the thread group. */ public PooledFatPipe(Producer<T, S> producer, int poolSize, ExceptionListener listener) { this(producer, poolSize, listener, producer.getClass().getSimpleName()); }