I should create Thread as ProducerThread and ConsumerThread those execute sequentially and put elements to queue. In this implementation I used ArrayList.
How might I convert an ArrayList object to integer Array in java.
This is my ConsumerThread class.
import java.util.ArrayList;
public class ConsumerThread implements Runnable {
ArrayList<Integer> queue = new ArrayList<Integer>();
public ConsumerThread(ArrayList<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
synchronized(queue) {
int value;
while(true) {
try {
queue.wait();
System.out.println("Consumer Started");
value = queue.remove(0);
System.out.println("Consumer thread consumes " + value);
System.out.println("Elements in Queue = " + queue);
Thread.sleep(1000);
queue.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
This is my ProducerThread class.
import java.util.ArrayList;
public class ProducerThread implements Runnable {
ArrayList<Integer> queue = new ArrayList<Integer>();
public ProducerThread(ArrayList<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
synchronized(queue) {
int value = 10;
while(true) {
try {
queue.notify();
System.out.println("Producer Started");
System.out.println("Producer adding value = " + value + " to Queue");
queue.add(value);
value = value + 10;
//Thread.sleep(1000);
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
This is my main class.
import java.util.ArrayList;
public class ThreadTest {
public static void main(String[] args) {
ArrayList<Integer> queue = new ArrayList<Integer>();
Thread producer = new Thread(new ProducerThread(queue));
Thread consumer = new Thread(new ConsumerThread(queue));
producer.start();
consumer.start();
System.out.println("Starting");
}
}