2016-05-03 33 views
3

私はThreadPoolExecuterの1つで複数のスレッドを同時に実行できます。 Runnableでは、別のスレッドでメソッドを実行したいので、executeメソッドで別のスレッド(スレッドA)を作成しましたが、今度はスレッドAの結果をエグゼキュータスレッドで実行したいと考えています。 私は一つのサンプルを明確にしましょう: 呼び出し元スレッドでインターフェイスコールバックを呼び出すにはどうすればよいですか?

ThreadPoolExecuter threadPool = Executors.newFixedThreadPool(5); 

threadPool.execute(new Runnable() { 
      @Override 
      public void run() { 

       // do something in threadPool thread 

       // call method in thread A 
       getInfo(new QueryExecutorInterface() { 
        @Override 
        public void onPostExecute(Cursor cursor) { 

         // do other thing in threadPool thread again. 

        } 
       }); 
      } 
     }); 

QueryExecutorInterface

私は Aスレッドすると ThreadPoolスレッドになります渡したいきた私のインタフェースです。

  class A extend Thread { 

      @Override 
      public void run() { 

       // do something in thread A. 

       queryExecutorInterface.onPostExecute(cursor); 
      } 
      } 

PS:私はコールリスナーが、私はスレッドAになり得る方法を以下のようにコールバックしましたように私はReentrantLockクラスを使用して代わりのスレッドAを使用して、このシナリオを修正することができます。しかし、私はこれ以上のレイヤーを持っているので、私はロックを使いたくありません。

答えて

1

ThreadPoolに別のRunnableを追加するだけで済みます。だからあなたは最終的にThreadPoolを作らなければなりません:

final ThreadPoolExecuter threadPool = Executors.newFixedThreadPool(5); // note the final modifier 

threadPool.execute(new Runnable() { 
    @Override 
    public void run() { 

     // do something in threadPool thread 
     // call method in thread A 
     getInfo(new QueryExecutorInterface() { 
      @Override 
      public void onPostExecute(Cursor cursor) { 
       threadPool.execute(new Runnable() { // adding another callback so it runs in threadpool 
        @Override 
        public void run() { 
         // do the thing here 
        } 
       }); 
      } 
     }); 
    } 
}); 
+0

あなたの返事に感謝します。 解決策には問題は1つありますが、問題はありません。 'threadPool'に100個のタスクを追加すると、データを取得した後、新しい' runnable'が 'threadPool queue'の最後に移動します。この' runnable' ASAPを 'threadPool'キューで実行する解決策はありますか? –

+0

次に、何らかのロックが必要です。しかしそれは、応答が来るまでプール内のスレッドをブロックします。私はあなたがそれをしないことをお勧めします。 一方、2つの独立したスレッドプールを持つことができます。リクエストを送信するためのリクエストとレスポンスを処理するリクエスト。 –

+1

私は良い方法は、http://stackoverflow.com/questions/3545623/how-to-implement-priorityblockingqueue-with-threadpoolexecutor-and-custom-tasksのような 'PriorityThreadPoolExecuter'を実装すると思います。ご回答有難うございます –

関連する問題