Last active
February 11, 2017 15:17
-
-
Save jleedev/03b61ba7066c5c4051770245c03c6e06 to your computer and use it in GitHub Desktop.
java producer consumer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.*; | |
public class Main { | |
static void run(int inputSize, int batchSize) throws Exception { | |
ExecutorService executor = Executors.newCachedThreadPool(); | |
BlockingQueue<Integer> q = new LinkedBlockingQueue<>(2 * batchSize); | |
Future<Void> p = executor.submit(() -> { | |
for (int i = 0; i < inputSize; i++) { | |
q.put(i); | |
} | |
return null; | |
}); | |
while (!p.isDone() || !q.isEmpty()) { | |
executor.submit(() -> { | |
List<Integer> lst = new ArrayList<>(); | |
q.drainTo(lst, batchSize); | |
System.out.println(lst); | |
return null; | |
}).get(); | |
} | |
executor.shutdown(); | |
} | |
public static void main(String[] args) throws Exception { | |
run(18, 5); | |
run(0, 2); | |
run(10, 5); | |
run(10, 4); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment