Created
April 4, 2011 00:05
-
-
Save newobj/900954 to your computer and use it in GitHub Desktop.
Pure java impl of problem described at http://www.bestinclass.dk/index.clj/2009/09/scala-vs-clojure-round-2-concurrency.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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