Sunday, January 8, 2012

Using Blocking Queues


package com.oreilly.tiger.ch10;


import java.io.PrintStream;

import java.util.Date;

import java.util.concurrent.BlockingQueue;


public class Producer extends Thread {


private BlockingQueue q;

private PrintStream out;


public Producer(BlockingQueue q, PrintStream out) {

setName("Producer");
this.q = q;

this.out = out;

}



public void run( ) {

try {

while (true) {

q.put(produce( ));

}

} catch (InterruptedException e) {

out.printf("%s interrupted: %s", getName( ), e.getMessage( ));

}

}


private String produce( ) {

while (true) {

double r = Math.random( );



// Only goes forward 1/10 of the time

if ((r*100) < 10) {

String s = String.format("Inserted at %tc", new Date( ));

return s;

}

}

}

}

0 comments:

Post a Comment

Tu comentario será moderado la primera vez que lo hagas al igual que si incluyes enlaces. A partir de ahi no ser necesario si usas los mismos datos y mantienes la cordura. No se publicarán insultos, difamaciones o faltas de respeto hacia los lectores y comentaristas de este blog.