OnJava8-Examples/concurrent/StickHolder.java

28 lines
762 B
Java
Raw Normal View History

2016-12-29 17:05:59 -08:00
// concurrent/StickHolder.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2016-12-29 17:05:59 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.concurrent.*;
public class StickHolder {
private static class Chopstick {}
private Chopstick stick = new Chopstick();
private BlockingQueue<Chopstick> holder =
new ArrayBlockingQueue<>(1);
public StickHolder() { putDown(); }
public void pickUp() {
try {
holder.take(); // Blocks if unavailable
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
public void putDown() {
try {
holder.put(stick);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
}