Advertisement
fevzi02

Untitled

Feb 1st, 2023
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. class CONST
  5. {
  6. public static int n = 10;
  7.  
  8. public static List<Integer> list = new ArrayList<>();
  9.  
  10. public static int rem;
  11. }
  12.  
  13. public class Labfour2 {
  14.  
  15. public static void main(String[] args) {
  16.  
  17. BlockingQueue queue = new BlockingQueue();
  18.  
  19. Squares task1 = new Squares(queue);
  20. PrintSquares task2 = new PrintSquares(queue);
  21.  
  22. new Thread(task1).start();
  23. new Thread(task2).start();
  24. }
  25. }
  26. // Класс BlockingQueue, хранящий очередь
  27. class BlockingQueue{
  28.  
  29. private int product=0;
  30. // private int crt=0;
  31. public synchronized void get() {
  32. while (product<1) {
  33. try {
  34. wait();
  35. }
  36. catch (InterruptedException e) {
  37. }
  38. }
  39. product--;
  40. // System.out.println(CONST.list.get(0));
  41. CONST.rem = CONST.list.get(0);
  42. CONST.list.remove(0);
  43. notify();
  44. }
  45. public synchronized void put(int value) {
  46. while (product>=CONST.n) {
  47. try {
  48. wait();
  49. }
  50. catch (InterruptedException e) {
  51. }
  52. }
  53. product++;
  54.  
  55. CONST.list.add(value);
  56. // crt++;
  57. notify();
  58. }
  59. }
  60. // класс Производитель
  61. class Squares implements Runnable{
  62.  
  63. BlockingQueue store;
  64. Squares(BlockingQueue store){
  65. this.store=store;
  66. }
  67. public void run(){
  68. for (int i = 0; i <= CONST.n; i++) {
  69. store.put(i*i);
  70. }
  71. }
  72. }
  73. // Класс Потребитель
  74. class PrintSquares implements Runnable{
  75.  
  76. BlockingQueue store;
  77. PrintSquares(BlockingQueue store){
  78. this.store=store;
  79. }
  80. public void run(){
  81. for (int i = 0; i < CONST.n; i++) {
  82. store.get();
  83. System.out.println(CONST.rem);
  84. }
  85. }
  86. }
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement