Guest User

Untitled

a guest
Nov 23rd, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. package thread;
  2.  
  3. import java.util.Arrays;
  4. import java.util.concurrent.LinkedBlockingQueue;
  5.  
  6. public class Pool {
  7. private final Worker[] workers;
  8. private final LinkedBlockingQueue<Runnable> queue;
  9.  
  10. public Pool(int nThreads) {
  11. workers = new Worker[nThreads];
  12. queue = new LinkedBlockingQueue<>();
  13.  
  14. for (int i = 0; i < nThreads; ++i) {
  15. workers[i] = new Worker();
  16. workers[i].start();
  17. }
  18. }
  19.  
  20. public void push(Runnable task) {
  21. synchronized (queue) {
  22. queue.add(task);
  23. queue.notify();
  24. }
  25. }
  26.  
  27. public void join() {
  28. while (Arrays.stream(workers).anyMatch((worker) -> worker.busy));
  29. }
  30.  
  31. public final int size() {
  32. return queue.size();
  33. }
  34.  
  35. public final boolean isEmpty() {
  36. return queue.isEmpty();
  37. }
  38.  
  39. private class Worker extends Thread {
  40. boolean busy = false;
  41.  
  42. public void run() {
  43. Runnable task;
  44.  
  45. while (true) {
  46. synchronized (queue) {
  47. while (queue.isEmpty()) {
  48. try {
  49. busy = false;
  50. queue.wait();
  51. } catch (InterruptedException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. busy = true;
  56. task = queue.poll();
  57. }
  58.  
  59. try {
  60. task.run();
  61. } catch (RuntimeException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. }
  66. }
  67. }
  68.  
  69.  
  70. // // Usage
  71. // thread.Pool pool = new thread.Pool(8);
  72. // pool.push(() -> {
  73. // /* do something */
  74. // });
  75. // pool.join();
Add Comment
Please, Sign In to add comment