использование wait () и notify () при реализации шаблона пула в java - PullRequest
0 голосов
/ 06 апреля 2020

Я пытался реализовать шаблон пула, но wait () внутри getInstance () никогда не уведомляется, хотя у меня есть метод notifyAll () внутри метода releaseInstance (). У меня нет большого опыта работы с потоками, поэтому мое решение здесь основано на том, что я мог бы извлечь asp из inte rnet, и это, похоже, не работает :).

public class PoolsOfObjects {
    int size = 3;
    int counter = 0;
    int temp = 0;
    boolean checker = false;
    ServiceObject[] arr = new ServiceObject[size];
    public ServiceObject getInstance() throws InterruptedException {

        synchronized (arr) {
            while(counter>size) {
                System.out.println("wait begins");
                arr.wait();
            }
        }

        for(int i = 0; i<size; i++) {
            if(arr[i] != null) {
                return arr[i];
            }               
        }
        ServiceObject obj1 = new ServiceObject();
        counter++;
        return obj1;
    }


    public void releaseInstance(ServiceObject obj) {
        for(int i = 0; i<size; i++) {
            System.out.println(counter);
            if(arr[i] == null) {
                temp = i;
                arr[i] = obj;
                System.out.println(i+"->"+arr[i]);
                obj = null;
                counter--;
                synchronized (arr) {
                    System.out.println("break the wait");
                    arr.notifyAll();
                }
            }
        }
    }
}
...