Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.List;
- import java.util.Queue;
- import java.util.concurrent.SynchronousQueue;
- public class SuperMegaAwesomeMultithreading {
- public void processRecords(List<String> records) {
- SynchronousQueue<String> recordsToProcess = new SynchronousQueue<>();
- recordsToProcess.addAll(records);
- int processors = Runtime.getRuntime().availableProcessors();
- ProcessingThread threads[] = new ProcessingThread[processors];
- for (int i = 0; i < processors; i++) {
- threads[i] = new ProcessingThread(recordsToProcess);
- threads[i].start();
- }
- for (ProcessingThread thread : threads)
- try {
- thread.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- private static class ProcessingThread extends Thread {
- private final Queue<String> records;
- private ProcessingThread(Queue<String> records) {
- this.records = records;
- }
- @Override
- public void run() {
- while (true) {
- String record = records.poll();
- if (record == null)
- break;
- // todo: make some work with record
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment