Advertisement
Guest User

Untitled

a guest
May 28th, 2015
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. package threadsafe;
  2.  
  3. /**
  4. * Created by pyq on 4/19/15.
  5. */
  6. class Chopstick {
  7.  
  8. // TODO - change if need be
  9.  
  10. private final int numberAroundTable;
  11. private boolean isUsing;
  12.  
  13. public Chopstick(int numberAroundTable) {
  14. this.numberAroundTable = numberAroundTable;
  15. this.isUsing = false;
  16. }
  17.  
  18. public int getNumberAroundTable() {
  19. return numberAroundTable;
  20. }
  21. public synchronized void pickUp() {
  22. isUsing = true;
  23. }
  24. public synchronized void putDown() {
  25. isUsing = false;
  26. }
  27. public synchronized boolean isAvailable() {
  28. return isUsing == false;
  29. }
  30. }
  31.  
  32. //for DijkstraPhilosopher
  33.  
  34. @Override
  35. public boolean attemptEat(Chopstick left, Chopstick right, Callback callback) {
  36. //pick up the smaller number of chopsitck
  37. if(left.getNumberAroundTable() < right.getNumberAroundTable()) {
  38. if(left.isAvailable()) {
  39. callback.pickedUpChopstick(left);
  40. left.pickUp(false);
  41. if (right.isAvailable()) {
  42. callback.pickedUpChopstick(right);
  43. right.pickUp();
  44. return true;
  45. }
  46. callback.putDownChopstick(left);
  47. right.putDown();
  48. }
  49.  
  50. // In my opinion, Chopstick is thread safe, it ensures only one thread use a chopstick instance,
  51. //but is not threadthread in attemptEat
  52. // for example if 2 philosophers are trying to use a chopstick '3',
  53. //when they use check method isAvailable(), both return true, they might
  54. // use try to pickup this chopstick twice. It is a little like you've told me the Vector.
  55. //every method is thread safe, but it is possible
  56. // add an element twice.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement