Skip to content

Instantly share code, notes, and snippets.

@newobj
Created April 4, 2011 00:05
Show Gist options
  • Save newobj/900954 to your computer and use it in GitHub Desktop.
Save newobj/900954 to your computer and use it in GitHub Desktop.
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
public class Barber {
private final static int MaxSeats = 3;
public static void main(String[] args) throws InterruptedException {
final LinkedBlockingQueue<String> q = new LinkedBlockingQueue<String>(
MaxSeats);
// Barber thread
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
String cust = q.take();
System.out.println("Barber is cutting " + cust
+ "'s hair.");
Thread.sleep((long) (100 + Math.random() * 1000));
} catch (InterruptedException e) {
break;
}
}
}
}) {
}.start();
while (true) {
final String customerName = "Customer " + UUID.randomUUID();
// Customer threads
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(customerName
+ (q.offer(customerName) ? " took a seat."
: " gave up and walked away."));
}
}).start();
Thread.sleep((long) (100 + Math.random() * 1000));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment