Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package mocek;
- import java.util.ArrayList;
- import java.util.List;
- /**
- *
- * @author Lab
- */
- public class Mocek {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- User[] users = new User[15];
- for (int i = 0; i < users.length; i++) {
- users[i] = new User();
- users[i].start();
- }
- }
- }
- class Pula {
- static int INIT_SIZE = 5;
- static int MAX_SIZE = 10;
- List<Zasob> zasob = new ArrayList(INIT_SIZE);
- private static final Pula pula = new Pula();
- public static Pula getPula() {
- return pula;
- }
- private Pula() {
- for (int i = 0; i < INIT_SIZE; i++) {
- zasob.add(new Zasob());
- }
- }
- synchronized void put(Zasob z) {
- z.setResourceEmpty(!z.isResourceEmpty());
- notify();
- }
- /**
- * pobranie liczby z zasobu
- *
- * @return liczba przechowywana w zasobie
- */
- synchronized Zasob get() {
- while (true) {
- for (int i = 0; i < zasob.size(); i++) {
- if (zasob.get(i).isResourceEmpty()) {
- zasob.get(i).setResourceEmpty(false);
- return zasob.get(i);
- }
- }
- if (zasob.size() < MAX_SIZE) {
- zasob.add(new Zasob());
- zasob.get(zasob.size() - 1).setResourceEmpty(false);
- return zasob.get(zasob.size() - 1);
- }
- try {
- System.err.println("Czekam na zasób");
- wait();
- System.err.println("Doczekałem się na zasób");
- } catch (InterruptedException e) {
- }
- }
- }
- }
- class Zasob {
- /**
- * true gdy pusty
- */
- private boolean resourceEmpty = true;
- /**
- * konstruktor bezparametryczny
- */
- public Zasob() {
- }
- /**
- * @return the resourceEmpty
- */
- public boolean isResourceEmpty() {
- return resourceEmpty;
- }
- /**
- * @param resourceEmpty the resourceEmpty to set
- */
- public void setResourceEmpty(boolean resourceEmpty) {
- this.resourceEmpty = resourceEmpty;
- }
- }
- class User extends Thread {
- @Override
- public void run() {
- Zasob z = Pula.getPula().get();
- System.out.println("Dostałem zasób " + z);
- try {
- Thread.sleep(300);
- } catch (InterruptedException ex) {
- }
- System.out.println("Zwalniam zasób " + z);
- Pula.getPula().put(z);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement