Answer the question
In order to leave comments, you need to log in
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
because
for (int i = 0; i<5000;i++)
System.out.println(list.remove(i));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question