Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package threadsafe;
- /**
- * Created by pyq on 4/19/15.
- */
- class Chopstick {
- // TODO - change if need be
- private final int numberAroundTable;
- private boolean isUsing;
- public Chopstick(int numberAroundTable) {
- this.numberAroundTable = numberAroundTable;
- this.isUsing = false;
- }
- public int getNumberAroundTable() {
- return numberAroundTable;
- }
- public synchronized void pickUp() {
- isUsing = true;
- }
- public synchronized void putDown() {
- isUsing = false;
- }
- public synchronized boolean isAvailable() {
- return isUsing == false;
- }
- }
- //for DijkstraPhilosopher
- @Override
- public boolean attemptEat(Chopstick left, Chopstick right, Callback callback) {
- //pick up the smaller number of chopsitck
- if(left.getNumberAroundTable() < right.getNumberAroundTable()) {
- if(left.isAvailable()) {
- callback.pickedUpChopstick(left);
- left.pickUp(false);
- if (right.isAvailable()) {
- callback.pickedUpChopstick(right);
- right.pickUp();
- return true;
- }
- callback.putDownChopstick(left);
- right.putDown();
- }
- // In my opinion, Chopstick is thread safe, it ensures only one thread use a chopstick instance,
- //but is not threadthread in attemptEat
- // for example if 2 philosophers are trying to use a chopstick '3',
- //when they use check method isAvailable(), both return true, they might
- // use try to pickup this chopstick twice. It is a little like you've told me the Vector.
- //every method is thread safe, but it is possible
- // add an element twice.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement