Advertisement
Razzim

Wspolbiezne lab8

Jan 11th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. public class klasaGlowna {
  2. public static void main (String[] args) {
  3. widelec W1 = new widelec(1);
  4. widelec W2 = new widelec(2);
  5. widelec W3 = new widelec(3);
  6. widelec W4 = new widelec(4);
  7. widelec W5 = new widelec(5);
  8.  
  9. filozof F1 = new filozof(1, W5, W1);
  10. filozof F2 = new filozof(2, W1, W2);
  11. filozof F3 = new filozof(3, W2, W3);
  12. filozof F4 = new filozof(4, W3, W4);
  13. filozof F5 = new filozof(5, W4, W5);
  14.  
  15.  
  16.  
  17. F1.start();
  18. F2.start();
  19. F3.start();
  20. F4.start();
  21. F5.start();
  22.  
  23. try {
  24. F1.join();
  25. F2.join();
  26. F3.join();
  27. F4.join();
  28. F5.join();
  29. } catch(Exception err) { /*...*/ }
  30.  
  31. System.out.println("Klasa główna");
  32. }
  33. }
  34.  
  35.  
  36.  
  37.  
  38. public class filozof extends Thread {
  39. public int id;
  40. public widelec prawy;
  41. public widelec lewy;
  42.  
  43. public void run(){
  44.  
  45. for (int i=0; i<100; i++){
  46.  
  47. if (lewy.wUzyciu == 0)
  48. {
  49. lewy.wUzyciu = 1;
  50. System.out.println("Lewy widelec podniesiony przez filozofa nr " + id);
  51. }
  52. else
  53. System.out.println("Lewy widelec filozofa nr " + id + " jest już w użyciu");
  54.  
  55. if (prawy.wUzyciu == 0)
  56. {
  57. prawy.wUzyciu = 1;
  58. System.out.println("Prawy widelec podniesiony przez filozofa nr " + id);
  59. }
  60. else
  61. System.out.println("Prawy widelec filozofa nr " + id + " jest już w użyciu");
  62.  
  63. System.out.println();
  64.  
  65. try {
  66. Thread.sleep( (int) (Math.random()*100.0) );
  67. } catch(InterruptedException err) { /*...*/ }
  68.  
  69. lewy.wUzyciu = 0;
  70. prawy.wUzyciu = 0;
  71. }
  72. }
  73.  
  74. public filozof(int a, widelec p, widelec l)
  75. {
  76. id = a;
  77. prawy = p;
  78. lewy = l;
  79. }
  80. }
  81.  
  82.  
  83.  
  84. public class widelec {
  85. public int wUzyciu;
  86. public int id;
  87.  
  88. public widelec(int a)
  89. {
  90. id = a;
  91. wUzyciu = 0;
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement