Main Class
package test;
import java.util.concurrent.*;
public class Main {
public static CompletionService
private final static int poolSize = 4;
public static volatile int counter = 1;
/**
* @param args
*/
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(poolSize);
cs = new ExecutorCompletionService
(new Producer()).run();
(new Consumer()).run();
}
}
Producer Class
package test;
public class Producer extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Submitting Task " + i);
Main.cs.submit(new Task1(i));
}
}
}
Consumer Class
package test;
import java.util.concurrent.ExecutionException;
public class Consumer extends Thread {
@Override
public void run() {
int i = 0;
while(true) {
try {
Integer j = Main.cs.take().get();
i++;
System.out.println("Took out task " + i + " with result:" + j);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Task Class
package test;
import java.util.concurrent.Callable;
public class Task1 implements Callable {
int id;
Task1 (int i){
id = i;
}
public Object call() throws Exception {
Thread.sleep(1000*Main.counter);
Main.counter++;
System.out.println("In Task1 and just iterated counter to:" + Main.counter);
return Main.counter;
}
}
No comments:
Post a Comment