title: Java thread as an event loop thread
body: <p>I want to use a thread as an event loop thread. I mean a Java thread with a "QThread like behaviour" (<code>t2</code> in the following example). Explanation:</p>
  
  <p>I have a thread <code>t1</code> (main thread) and a thread <code>t2</code> (a worker thread). I want that <code>method()</code>, called from <code>t1</code>, is executed in <code>t2</code> thread.</p>
  
  <p>Currently, I made this code (it works, but I don't like it):</p>
  
  <p>-Thread <strong>t1</strong> (Main thread, UI thread for example):</p>
  
  <pre><code>//...
  // Here, I want to call "method()" in t2's thread
  Runnable event = new Runnable() {
  
      @Override
      public void run()
      {
          t2.method(param);
      }
  };
  t2.postEvent(event);
  //...
  </code></pre>
  
  <p>-Thread <strong>t2</strong>:</p>
  
  <pre><code>//...
  Queue&lt;Runnable&gt; eventLoopQueue = new ConcurrentLinkedQueue&lt;Runnable&gt;();
  //...
  @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);
  }
  </code></pre>
  
  <p>This solution is ugly. I don't like the "always-working" main loop in <code>t2</code>, the new <code>Runnable</code> allocation each time in <code>t1</code>... My program can call <code>method</code> something like 40 times per second, so I need it to be efficient.</p>
  
  <p>I'm looking for a solution that should be used on Android too (I know the class <a href="https://developer.android.com/reference/android/os/Looper.html" rel="nofollow">Looper</a> for Android, but it's only for Android, so impossible)</p>