I want to use a thread as an event loop thread. I mean a Java thread with a "QThread like behaviour" (t2
in the following example). Explanation:
I have a thread t1
(main thread) and a thread t2
(a worker thread). I want that method()
, called from t1
, is executed in t2
thread.
Currently, I made this code (it works, but I don't like it):
-Thread t1 (Main thread, UI thread for example):
//...
// Here, I want to call "method()" in t2's thread
Runnable event = new Runnable() {
@Override
public void run()
{
t2.method(param);
}
};
t2.postEvent(event);
//...
-Thread t2:
//...
Queue<Runnable> eventLoopQueue = new ConcurrentLinkedQueue<Runnable>();
//...
@Override
public void run()
{
//...
Runnable currentEvent = null;
while (!bMustStop) {
while ((currentEvent = eventLoopQueue.poll()) != null) {
currentEvent.run();
}
}
//...
}
public void method(Param param)
{
/* code that should be executed in t2's thread */
}
public void postEvent(Runnable event)
{
eventLoopQueue.offer(event);
}
This solution is ugly. I don't like the "always-working" main loop in t2
, the new Runnable
allocation each time in t1
... My program can call method
something like 40 times per second, so I need it to be efficient.
I'm looking for a solution that should be used on Android too (I know the class Looper for Android, but it's only for Android, so impossible)
Consider using BlockingQueue
instead of Queue
for its method take()
will block the thread until an element is available on the queue, thus not wasting cycles like poll()
does.