Advertisement
Guest User

Untitled

a guest
Jul 5th, 2010
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1. import mutex.Lock;
  2. import mutex.Mutex;
  3. public class Test{
  4. public static void main(String args[]){
  5. new Test().process();
  6. }
  7.  
  8. void process(){
  9. int size = 100;
  10. Lock lock = new Mutex(size);
  11. inc(size, lock);
  12. }
  13. void inc(int np, Lock lock){
  14. MyThread t[] = new MyThread[np];
  15. for(int i=0;i<np;i++){
  16. t[i] = new MyThread(i, lock);
  17. t[i].start();
  18. int v = t[i].getCountValue();
  19. System.out.println("count value:t["+i+"]"+v+" "+(i==v?"":"XXX"));
  20. }
  21. }
  22. }
  23.  
  24.  
  25.  
  26. import mutex.Lock;
  27. import mutex.Mutex;
  28. public class MyThread extends Thread{
  29. private int pid;
  30. private Lock lock;
  31. private static int count = 0;
  32.  
  33. public MyThread(int pid, Lock lock){
  34. this.pid = pid;
  35. this.lock = lock;
  36. }
  37.  
  38. public void run(){
  39. this.lock.lock(this.pid);
  40. increament();
  41. //decreament();
  42. this.lock.unlock(this.pid);
  43. }
  44.  
  45. public void increament(){
  46. count++;
  47. }
  48.  
  49. public void decreament(){
  50. count--;
  51. }
  52.  
  53. public int getCountValue(){
  54. return this.count;
  55. }
  56. }
  57.  
  58.  
  59.  
  60. package mutex;
  61.  
  62. public interface Lock{
  63. void lock(int pid);
  64. void unlock(int pid);
  65. }
  66.  
  67.  
  68.  
  69. package mutex;
  70.  
  71. public class Mutex implements Lock{
  72. int N;
  73. boolean takeANumber[];
  74. int valueOfProcess[];
  75. public Mutex(int n){
  76. this.N = n;
  77. takeANumber = new boolean[N];
  78. valueOfProcess = new int[N];
  79. for(int i=0;i<N;i++){
  80. takeANumber[i] = false;
  81. valueOfProcess[i] = 0;
  82. }
  83. }
  84.  
  85. public void lock(int pid){
  86. // 1. take a number
  87. takeANumber[pid] = true;
  88. for(int i=0;i<N;i++){
  89. if(valueOfProcess[i]>valueOfProcess[pid]){
  90. valueOfProcess[pid] = valueOfProcess[i];
  91. }
  92. }
  93. valueOfProcess[pid]++; // line up
  94. takeANumber[pid] = false;
  95.  
  96. // 2. check whose number is the smallest
  97. for(int i=0;i<N;i++){
  98. while(takeANumber[i]); // if other processes are taking a number, wait for them finishing that procedure.
  99.  
  100. while((valueOfProcess[i]!=0 &&
  101. ((valueOfProcess[i]<valueOfProcess[pid])||
  102. (valueOfProcess[i]==valueOfProcess[pid]&&i<pid)))); // busy wait
  103. }
  104. }
  105.  
  106. public void unlock(int pid){
  107. valueOfProcess[pid] = 0;
  108. }
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement