0

ソケット接続で新しいスレッドを作成するアプリケーションがあります。このスレッドからExecutorServiceにCallableを送信したいと思います。Callableはコマンドライン引数を介してプログラムを実行する必要があるため、接続スレッドを介してこれを実行したくありません。

問題は、スレッド数が設定されているExecutorServiceにCallableを送信する方法がわからないことです。

シングルトンでこれを実行し、CallableをExecutorServiceインスタンスに送信するための送信メソッドを作成することを検討しましたが、APIに慣れていないため、これが適切かどうかはわかりませんでした。

どんな助けでも大歓迎です、ありがとう。

4

3 に答える 3

11

やってみます

 static final ExecutorService service = Executors.newFixedThreadPool(4);

 Callable call = 
 service.submit(call);
于 2012-04-24T14:55:48.727 に答える
3

これが私があなたの問題についてオンラインで見つけたいくつかのコードです:

public class CallableExample {

  public static class WordLengthCallable
        implements Callable {
    private String word;
    public WordLengthCallable(String word) {
      this.word = word;
    }
    public Integer call() {
      return Integer.valueOf(word.length());
    }
  }

  public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<Future≶Integer>>();
    for (String word: args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable);
      set.add(future);
    }
    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();
    }
    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
  }
}
于 2012-04-24T14:54:38.860 に答える
2

メソッドsubmit()があります:

ExecutorService service = Executors.(get the one here you like most)();
Callable<Something> callable = (your Callable here);
Future<AnotherSomething> result = service.submit(callable);

エグゼキュータサービスを使用する場合は、タスクが実際にいつ開始されるかを制御できないことに注意してください。

于 2012-04-24T15:06:22.553 に答える