public class Producer extends Thread {
static List<String> list = new ArrayList<String>();
public static void main(String[] args) {
ScheduledExecutorService executor = Executors
.newScheduledThreadPool(12);
int initialDelay = 5;
int pollingFrequency = 5;
Producer producer = new Producer();
@SuppressWarnings({ "rawtypes", "unused" })
ScheduledFuture schedFutureProducer = executor.scheduleWithFixedDelay(
producer, initialDelay, pollingFrequency, TimeUnit.SECONDS);
for (int i = 0; i < 3; i++) {
Consumer consumer = new Consumer();
@SuppressWarnings({ "rawtypes", "unused" })
ScheduledFuture schedFutureConsumer = executor
.scheduleWithFixedDelay(consumer, initialDelay,
pollingFrequency, TimeUnit.SECONDS);
}
}
@Override
public void run() {
list.add("object added to list is " + System.currentTimeMillis());
///adding in list become slow also because of synchronized behavior
}
}
class Consumer extends Thread {
@Override
public void run() {
getObjectFromList();
}
private void getObjectFromList() {
synchronized (Producer.list) {
if (Producer.list.size() > 0) {
System.out.println("Object name removed by "
+ Thread.currentThread().getName() + "is "
+ Producer.list.get(0));
Producer.list.remove(Producer.list.get(0));
}
}
}
}