import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class ArrayBlockingQueueTest {
ArrayBlockingQueue<String> b = new ArrayBlockingQueue<String>(10, true);
Thread t1;
Thread t2;
String text = "India’s recent series of power blackouts, "
+ "in which 600 million people lost electricity for "
+ "several days, reminds us of the torrid pace at which "
+ "populations in the developing world have moved onto "
+ "the powergrid. Unfortunately, this great transition "
+ "has been so rapid that infrastructure has mostly been "
+ "unable to meet demand. India itself has failed to meets "
+ "its own power capacity addition targets every year since "
+ "1951. This has left roughly one quarter of the country’s "
+ "population without any (legal) access to electricity. "
+ "That’s 300 million people out of a population of 1.2 "
+ "billion. Indeed, it is the daily attempt of the underserved "
+ "to access power that may have led to India’s recent grid crash.";
class Writing implements Runnable
{
@Override
public void run() {
int i = 0;
String [] p = text.split(" ");
while(true)
{
try {
b.put(p[i]);
} catch (InterruptedException e) {
break;
}
i++;
if(i == p.length)
i = 0;
}
}
}
class Reading implements Runnable
{
@Override
public void run() {
while(true)
{
try {
for(int i = 0; i < 5; i++)
{
String t = b.poll(500, TimeUnit.MILLISECONDS);
System.out.print(t + " ");
}
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
}
}
public void Stop()
{
t1.interrupt();
t2.interrupt();
}
public ArrayBlockingQueueTest() {
t1 = new Thread(new Writing());
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2 = new Thread(new Reading());
t2.start();
}
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueueTest a = new ArrayBlockingQueueTest();
Thread.sleep(6000);
a.Stop();
}
}