Advertisement
reage

TicketClass

Nov 14th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1.  
  2. package threads;
  3.  
  4.  
  5. public class Ticket extends Thread {
  6. private int num;
  7. boolean reserved;
  8. static int bilety[] = new int[3];
  9.  
  10.  
  11. public Ticket(int num) {
  12. this.num = num;
  13. this.reserved = false;
  14. }
  15.  
  16. public Ticket(String string) {
  17.  
  18. }
  19.  
  20. public String toString() {
  21. return "Bilet [num = " + num + "]";
  22. }
  23.  
  24. public void run() {
  25. int i = 0;
  26. for(int j = 0; j < 6; j++)
  27. {
  28. while (!reserved)
  29. {
  30. for(i = 0; i < 3; i++)
  31. {
  32. if(bilety[i] == 0)
  33. {
  34. bilety[i] = 1;
  35. reserved = true;
  36. System.out.println("Wątek nr." + num + " zarezerwował bilet nr." + (i+1));
  37. break;
  38. }
  39. }
  40. try {
  41. sleep(1000);
  42. } catch (InterruptedException e) {
  43. System.out.println("Przerwano wątek nr." + num);
  44. return;
  45. }
  46. }
  47.  
  48. if(j > 0)
  49. {
  50. bilety[i] = 0;
  51. System.out.println("Wątek nr." + num + " zwolnił rezerwację biletu nr." + (i+1));
  52. break;
  53. }
  54.  
  55. try {
  56. sleep(1000);
  57. } catch (InterruptedException e) {
  58. System.out.println("Przerwano wątek nr:" + num);
  59. return;
  60. }
  61.  
  62. }
  63. }
  64.  
  65. public static void main(String[] args) {
  66.  
  67.  
  68. Ticket b[] = new Ticket[10];
  69. for(int k = 0; k < 10; k++)
  70. {
  71. b[k] = new Ticket(k+1);
  72. //System.out.println(b[k]);
  73. b[k].start();
  74.  
  75. }
  76.  
  77.  
  78. }
  79.  
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement