Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. class Pojemnik
  2. {
  3. private int liczba;
  4. synchronized public int pobierz() {
  5. System.out.println("Z pojemnika pobierana jest wartosc: " +
  6. liczba);
  7. return liczba;
  8. }
  9. synchronized public void wstaw(int liczba) {
  10. System.out.println("Do pojemnika wstawiana jest wartosc: " +
  11. liczba);
  12. this.liczba = liczba;
  13. }
  14. }
  15.  
  16. class Producent implements Runnable {
  17. Pojemnik p;
  18. Producent(Pojemnik p) {
  19. this.p = p;
  20. }
  21. public void run() {
  22. for (int i = 1; i <= 10; i++) {
  23. try {
  24. Thread.sleep((int) (100 * Math.random()));
  25. }
  26. catch (InterruptedException e) { }
  27. p.wstaw(i);
  28. }
  29. }
  30. }
  31.  
  32. class Konsument implements Runnable {
  33. Pojemnik p;
  34. Konsument(Pojemnik p) {
  35. this.p = p;
  36. }
  37. public void run() {
  38. for (int i = 1; i <= 10; i++) {
  39. try {
  40. Thread.sleep((int) (100 * Math.random()));
  41. }
  42. catch (InterruptedException e){ }
  43. p.pobierz();
  44. }
  45. }
  46. }
  47.  
  48. public class PCProblem {
  49. public static void main(String[] args) {
  50. Pojemnik poj = new Pojemnik();
  51. Producent prod = new Producent(poj);
  52. Konsument kons = new Konsument(poj);
  53. Thread watek1 = new Thread(prod);
  54. Thread watek2 = new Thread(kons);
  55. watek1.start();
  56. watek2.start();
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement