Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Pojemnik
- {
- private int liczba;
- synchronized public int pobierz() {
- System.out.println("Z pojemnika pobierana jest wartosc: " +
- liczba);
- return liczba;
- }
- synchronized public void wstaw(int liczba) {
- System.out.println("Do pojemnika wstawiana jest wartosc: " +
- liczba);
- this.liczba = liczba;
- }
- }
- class Producent implements Runnable {
- Pojemnik p;
- Producent(Pojemnik p) {
- this.p = p;
- }
- public void run() {
- for (int i = 1; i <= 10; i++) {
- try {
- Thread.sleep((int) (100 * Math.random()));
- }
- catch (InterruptedException e) { }
- p.wstaw(i);
- }
- }
- }
- class Konsument implements Runnable {
- Pojemnik p;
- Konsument(Pojemnik p) {
- this.p = p;
- }
- public void run() {
- for (int i = 1; i <= 10; i++) {
- try {
- Thread.sleep((int) (100 * Math.random()));
- }
- catch (InterruptedException e){ }
- p.pobierz();
- }
- }
- }
- public class PCProblem {
- public static void main(String[] args) {
- Pojemnik poj = new Pojemnik();
- Producent prod = new Producent(poj);
- Konsument kons = new Konsument(poj);
- Thread watek1 = new Thread(prod);
- Thread watek2 = new Thread(kons);
- watek1.start();
- watek2.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement