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();
}
}
}
for (int i = 0; i<5000;i++)
System.out.println(list.remove(i));