C
C
Charik6352021-05-25 18:03:02
Java
Charik635, 2021-05-25 18:03:02

Why is OutofBoundException thrown when reading from an array with wait and notify and only exactly half of the values ​​are read?

Here is the code

package MultiThreading;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class WaitNotify {
    private List<Integer> list = new ArrayList<>();
   private Random random = new Random();
    public static void main(String[] args) throws InterruptedException {
        WaitNotify wot = new WaitNotify();
        Thread thread1  = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    wot.producer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    wot.consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

    }

    /**
     *Методы wait и notify предназначены для разделения монитора между потоками
     *
     */
    private void producer() throws InterruptedException {
        synchronized (list){
            System.out.println("Thread is running");
            for (int i = 0; i<5000;i++)
            list.add(random.nextInt(100));
            System.out.println(list.size());
            list.wait();
           
       }
        }

    private void consumer()throws InterruptedException{
    synchronized (list){

        for (int i = 0; i<5000;i++)
        System.out.println(list.remove(i));
        list.notify();


    }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Shitskov, 2021-05-25
@Charik635

because

for (int i = 0; i<5000;i++)
        System.out.println(list.remove(i));

Each pass removes one element from the list. By the 2500th pass, 2500 values ​​have been removed from the list and the remaining list length is 2500...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question