123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- /**
- * MCS Media Computer Software
- * Copyright 2012 by Wilfried Klaas
- * Project: MCSUtils
- * File: ThreadUtilities.java
- * EMail: W.Klaas@gmx.de
- * Created: 30.03.2012 Willie
- */
- package de.mcs.utils.threads;
- import java.util.Queue;
- import java.util.concurrent.ConcurrentLinkedQueue;
- /**
- * @author Willie
- *
- */
- public class ThreadUtilities {
- private static Thread consumerThread;
- private static Queue<Runnable> queue = new ConcurrentLinkedQueue<Runnable>();
- private static class ConsumerThread implements Runnable {
- private Thread activeThread;
- public void run() {
- while (true) {
- if ((activeThread == null) || (!activeThread.isAlive())) {
- Runnable poll = queue.poll();
- if (poll != null) {
- activeThread = invoke(poll);
- } else {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- // e.printStackTrace();
- }
- }
- }
- // Thread.currentThread();
- Thread.yield();
- }
- }
- };
- public static Thread invoke(Runnable runnable) {
- Thread thread = new Thread(runnable);
- thread.start();
- return thread;
- }
- public static void invokeQueued(Runnable runnable) {
- if (consumerThread == null) {
- consumerThread = new Thread(new ConsumerThread());
- consumerThread.setDaemon(true);
- consumerThread.setName("background consumer thread");
- consumerThread.start();
- }
- queue.offer(runnable);
- }
- public static boolean invokeAndWait(int maxTimeSec, Runnable runnable) {
- Thread thread = invoke(runnable);
- long stop = System.currentTimeMillis() + (maxTimeSec * 1000);
- while (thread.isAlive() && (stop > System.currentTimeMillis())) {
- Thread.yield();
- }
- if (thread.isAlive()) {
- thread.interrupt();
- return false;
- }
- return true;
- }
- }
|