import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
public class Primes {
BlockingQueue<Integer> generateIntegers() {
final BlockingQueue<Integer> q = new SynchronousQueue<Integer>();
new Thread() {
@Override
public void run() {
for (int i = 2; true; i++) {
try {
q.put(i);
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(1);
}
}
}
}.start();
return q;
}
BlockingQueue<Integer> filterMultiples(final BlockingQueue<Integer> in,
final int prime) {
final BlockingQueue<Integer> out = new SynchronousQueue<Integer>();
new Thread() {
@Override
public void run() {
while (true) {
try {
int i = in.take();
if (i % prime != 0) {
out.put(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(1);
}
}
}
}.start();
return out;
}
BlockingQueue<Integer> sieve() {
final BlockingQueue<Integer> out = new SynchronousQueue<Integer>();
new Thread() {
@Override
public void run() {
BlockingQueue<Integer> q = generateIntegers();
while (true) {
try {
int prime = q.take();
out.put(prime);
q = filterMultiples(q, prime);
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(1);
}
}
}
}.start();
return out;
}
public static void main(String[] args) {
BlockingQueue<Integer> primes = new Primes().sieve();
while (true) {
try {
System.out.println(primes.take());
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(1);
}
}
}
}