Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
124
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.LinkedList;
  2. import java.util.logging.Level;
  3. import java.util.logging.Logger;
  4.  
  5. /**
  6. *
  7. * @author Jakub
  8. */
  9. public class MyThread {
  10. public static void main(String[] args)throws InterruptedException {
  11. final PC pc = new PC();
  12. Thread t1 = new Thread(new Runnable() {
  13. @Override
  14. public void run()
  15. {
  16. try {
  17. pc.produce();
  18. } catch (InterruptedException ex) {
  19. System.out.println(ex);
  20. }
  21. }
  22. });
  23. Thread t2 = new Thread(new Runnable() {
  24. @Override
  25. public void run()
  26. {
  27. try {
  28. pc.consume();
  29. } catch (InterruptedException ex) {
  30. System.out.println(ex);
  31. }
  32. }
  33. });
  34. t1.start();
  35. t2.start();
  36. t1.join();
  37. t2.join();
  38. }
  39.  
  40. public static class PC {
  41. LinkedList<Integer> list = new LinkedList<>();
  42. int capacity = 2;
  43. public void produce() throws InterruptedException
  44. {
  45. int value = 0;
  46. while (true) {
  47. synchronized (this)
  48. {
  49. while (list.size() == capacity)
  50. wait();
  51. list.add(value++);
  52. notify();
  53. }
  54. }
  55. }
  56. public void consume() throws InterruptedException
  57. {
  58. while (true) {
  59. synchronized (this)
  60. {
  61. while (list.size() == 0)
  62. wait();
  63. list.removeFirst();
  64. notify();
  65. }
  66. }
  67. }
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement