AsyncWorker.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package me.km.scheduler;
  2. import java.util.concurrent.ConcurrentLinkedQueue;
  3. public class AsyncWorker {
  4. private final ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<>();
  5. private final Thread worker;
  6. public AsyncWorker() {
  7. worker = new Thread(() -> run());
  8. }
  9. public void start() {
  10. worker.start();
  11. }
  12. public void stop() {
  13. while(worker.isAlive()) {
  14. synchronized(worker) {
  15. worker.interrupt();
  16. }
  17. try {
  18. worker.join(100);
  19. } catch(InterruptedException ex) {
  20. }
  21. }
  22. }
  23. private void run() {
  24. while(true) {
  25. synchronized(worker) {
  26. try {
  27. worker.wait();
  28. } catch(InterruptedException ex) {
  29. return;
  30. }
  31. }
  32. while(true) {
  33. if(tasks.isEmpty()) {
  34. break;
  35. }
  36. Runnable r = tasks.poll();
  37. try {
  38. r.run();
  39. } catch(Exception ex) {
  40. System.out.println("A worker task has thrown an exception:");
  41. ex.printStackTrace();
  42. }
  43. }
  44. }
  45. }
  46. public void add(Runnable r) {
  47. tasks.add(r);
  48. synchronized(worker) {
  49. worker.notify();
  50. }
  51. }
  52. public boolean hasWork() {
  53. return !tasks.isEmpty();
  54. }
  55. }