Skip to content

Instantly share code, notes, and snippets.

Created August 8, 2013 07:48
Show Gist options
  • Save anonymous/6182478 to your computer and use it in GitHub Desktop.
Save anonymous/6182478 to your computer and use it in GitHub Desktop.
You are given a paragraph , which contain n number of words, you are given m threads. What you need to do is , each thread should print one word and give the control to next thread, this way each thread will keep on printing one word , in case last thread come, it should invoke the first thread. Printing will repeat until all the words are print…
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ArrayBlockingQueue;
public class WordsPrinter {
static class Printer extends Thread {
private final ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(1);
private String[] words;
private Printer next;
private CountDownLatch latch;
private int index;
private int n;
private boolean done = false;
public Printer(Printer next, int n, String[] words, CountDownLatch latch, int index) {
this.index = index;
this.next = next;
this.words = words;
this.latch = latch;
this.n = n;
};
public void setNext(Printer next) {
this.next = next;
}
public void put(String word) {
try {
queue.put(word);
} catch (InterruptedException e) {
}
}
public void setDone(boolean done) {
this.done = done;
}
@Override
public void run() {
while(!done && index < words.length) {
String word = null;
try {
word = queue.take();
} catch (InterruptedException e) {}
if (!done) {
System.out.println(word);
}
if (index + 1 < words.length) {
next.put(words[index + 1]);
} else {
next.setDone(true);
next.put("");
}
index += n;
}
latch.countDown();
}
}
public static void main(String[] args) {
final String[] words = "this is a string that contains some words and it is really boring".split(" ");
int n = 15;
CountDownLatch latch = new CountDownLatch(n);
Printer[] printers = new Printer[n];
for(int i = n - 1; i >= 0; i--) {
if (i < n - 1) {
printers[i] = new Printer(printers[i + 1], n, words, latch, i);
} else {
printers[i] = new Printer(null, n, words, latch, i);
}
printers[i].start();
}
printers[n - 1].setNext(printers[0]);
printers[0].put(words[0]);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment