Guest User

SuperMegaAwesomeMultithreading

a guest
Jan 27th, 2015
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | None | 0 0
  1. import java.util.List;
  2. import java.util.Queue;
  3. import java.util.concurrent.SynchronousQueue;
  4.  
  5. public class SuperMegaAwesomeMultithreading {
  6.     public void processRecords(List<String> records) {
  7.         SynchronousQueue<String> recordsToProcess = new SynchronousQueue<>();
  8.         recordsToProcess.addAll(records);
  9.         int processors = Runtime.getRuntime().availableProcessors();
  10.         ProcessingThread threads[] = new ProcessingThread[processors];
  11.         for (int i = 0; i < processors; i++) {
  12.             threads[i] = new ProcessingThread(recordsToProcess);
  13.             threads[i].start();
  14.         }
  15.         for (ProcessingThread thread : threads)
  16.             try {
  17.                 thread.join();
  18.             } catch (InterruptedException e) {
  19.                 e.printStackTrace();
  20.             }
  21.     }
  22.  
  23.     private static class ProcessingThread extends Thread {
  24.         private final Queue<String> records;
  25.  
  26.         private ProcessingThread(Queue<String> records) {
  27.             this.records = records;
  28.         }
  29.  
  30.         @Override
  31.         public void run() {
  32.             while (true) {
  33.                 String record = records.poll();
  34.                 if (record == null)
  35.                     break;
  36.                 // todo: make some work with record
  37.             }
  38.         }
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment