LapisSea

Untitled

Feb 25th, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. package com.lapissea.amaze;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class MultiTasking{
  6.  
  7. private static class TaskedThread extends Thread{
  8.  
  9. Runnable task;
  10.  
  11. public TaskedThread(int id){
  12. super("TaskExecutor-"+id);
  13. }
  14.  
  15. @Override
  16. public void run(){
  17. while(true){
  18. if(hasWork()){
  19. task.run();
  20. task=null;
  21. ask();
  22. }else ask();
  23. }
  24. }
  25.  
  26. private void ask(){
  27. if(askOverlord(this))try{
  28. synchronized(this){
  29. wait();
  30. }
  31. }catch(InterruptedException e){
  32. throw new RuntimeException(e);
  33. }
  34. }
  35.  
  36. boolean hasWork(){
  37. return task!=null;
  38. }
  39.  
  40. }
  41.  
  42. public static boolean USE_MULTITHREADING=true;
  43. public static final int THREAD_CAP =8;
  44. private static final ArrayList<TaskedThread> FREE_THREADS=new ArrayList<>();
  45. private static final ArrayList<Runnable> QUEUE =new ArrayList<>();
  46. static{
  47. for(int i=0;i<THREAD_CAP;i++){
  48. TaskedThread thread=new TaskedThread(i);
  49. thread.start();
  50. FREE_THREADS.add(thread);
  51. }
  52. }
  53.  
  54. public synchronized static void run(Runnable task){
  55. if(!USE_MULTITHREADING)task.run();
  56. else if(!FREE_THREADS.isEmpty()){
  57. TaskedThread thread=FREE_THREADS.remove(0);
  58. thread.task=task;
  59. synchronized(thread){
  60. thread.notifyAll();
  61. }
  62. }else QUEUE.add(task);
  63. }
  64. public static boolean hasWork(){
  65. return !QUEUE.isEmpty();
  66. }
  67. private synchronized static boolean askOverlord(TaskedThread taskedThread){
  68. if(QUEUE.isEmpty()){
  69. FREE_THREADS.add(taskedThread);
  70. return true;
  71. }
  72. taskedThread.task=QUEUE.remove(0);
  73. return false;
  74. }
  75.  
  76. }
Add Comment
Please, Sign In to add comment