ThreadUtilities.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * MCS Media Computer Software
  3. * Copyright 2012 by Wilfried Klaas
  4. * Project: MCSUtils
  5. * File: ThreadUtilities.java
  6. * EMail: W.Klaas@gmx.de
  7. * Created: 30.03.2012 Willie
  8. */
  9. package de.mcs.utils.threads;
  10. import java.util.Queue;
  11. import java.util.concurrent.ConcurrentLinkedQueue;
  12. /**
  13. * @author Willie
  14. *
  15. */
  16. public class ThreadUtilities {
  17. private static Thread consumerThread;
  18. private static Queue<Runnable> queue = new ConcurrentLinkedQueue<Runnable>();
  19. private static class ConsumerThread implements Runnable {
  20. private Thread activeThread;
  21. public void run() {
  22. while (true) {
  23. if ((activeThread == null) || (!activeThread.isAlive())) {
  24. Runnable poll = queue.poll();
  25. if (poll != null) {
  26. activeThread = invoke(poll);
  27. } else {
  28. try {
  29. Thread.sleep(100);
  30. } catch (InterruptedException e) {
  31. // e.printStackTrace();
  32. }
  33. }
  34. }
  35. // Thread.currentThread();
  36. Thread.yield();
  37. }
  38. }
  39. };
  40. public static Thread invoke(Runnable runnable) {
  41. Thread thread = new Thread(runnable);
  42. thread.start();
  43. return thread;
  44. }
  45. public static void invokeQueued(Runnable runnable) {
  46. if (consumerThread == null) {
  47. consumerThread = new Thread(new ConsumerThread());
  48. consumerThread.setDaemon(true);
  49. consumerThread.setName("background consumer thread");
  50. consumerThread.start();
  51. }
  52. queue.offer(runnable);
  53. }
  54. public static boolean invokeAndWait(int maxTimeSec, Runnable runnable) {
  55. Thread thread = invoke(runnable);
  56. long stop = System.currentTimeMillis() + (maxTimeSec * 1000);
  57. while (thread.isAlive() && (stop > System.currentTimeMillis())) {
  58. Thread.yield();
  59. }
  60. if (thread.isAlive()) {
  61. thread.interrupt();
  62. return false;
  63. }
  64. return true;
  65. }
  66. }