7

質問がばかげているように聞こえる場合は、ご容赦ください。Executor を使い始めたばかりです。

この方法でスレッドを使用する既存のJavaアプリがあります-基本的にスタンドアロンスレッドが使用されます--

private Thread spawnThread( )
    {

        Thread t = new Thread()
        {
            String taskSnap = task.toString();
            public void run()
            {
                try
                {
                    println( task.run( null ) );
                }catch( InterruptedException e )
                {
                    println( "ITC - " + taskSnap + " interrupted " );
                }
            }
        };
        return t;
    }

上記からわかるように、関数は新しいスレッドを返します。

プログラムの main() 関数では、この方法で新しいスレッドが作成されます。

    taskThread = spawnThread();

    taskThread.start();

私がやりたいことは、エグゼキューターサービスを作成し(固定数のスレッドで)、新しいスレッドの作成/新しいスレッドによるタスクの実行をそのエグゼキューターに引き渡すことです。

私は Executor に非常に慣れていないので、知りたいのは、上記のコードを変更して、新しい別のスレッドが形成されるのではなく、スレッドプール内に新しいスレッドが作成されるようにする方法です。(スレッド プール内に) スレッドを作成するコマンドが表示されません。-> 上記のタスクをそのスレッドに渡します (上記のようにスタンドアロン スレッドではありません)。

この問題を解決する方法を教えてください。

4

3 に答える 3

9

メインでは、次のように書くことができます:

ExecutorService executor = Executors.newFixedThreadPool(nThreads);
executor.submit(new Runnable() {
    String taskSnap = task.toString();
    public void run() {
            try {
                println(task.run(null));
            } catch( InterruptedException e) {
                println("ITC - " + taskSnap + " interrupted ");
            }
    }
});

submit メソッドは、executor サービス内のスレッドの 1 つで Runnable を実行します。

注: エグゼキューター サービスが不要になった場合は、忘れずにシャットダウンしてください。そうしないと、プログラムが終了できなくなります。

于 2013-02-17T06:55:02.947 に答える
5

質問する前に調査を行います。Runnable を実装するクラスを作成し、executor サービスを使用して実行するという考え方です。

例: Java Concurrency (Multithreading) - チュートリアル

ワーカーの実装 (Runnable を実装):

package de.vogella.concurrency.threadpools;

/** * MyRunnable will count the sum of the number from 1 to the parameter * countUntil and then write the result to the console. * <p> * MyRunnable is the task which will be performed * * @author Lars Vogel * */

public class MyRunnable implements Runnable {
  private final long countUntil;

  MyRunnable(long countUntil) {
    this.countUntil = countUntil;
  }

  @Override
  public void run() {
    long sum = 0;
    for (long i = 1; i < countUntil; i++) {
      sum += i;
    }
    System.out.println(sum);
  }
} 

エグゼキューター サービスを使用してワーカー スレッドをトリガーする方法。

package de.vogella.concurrency.threadpools;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
  private static final int NTHREDS = 10;

  public static void main(String[] args) {
    //You can also use Executors.newSingleThreadExecutor() if you just need 1 thread
    ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
    for (int i = 0; i < 500; i++) {
      Runnable worker = new MyRunnable(10000000L + i);
      executor.execute(worker);
    }
    // This will make the executor accept no new threads
    // and finish all existing threads in the queue.
    executor.shutdown();
    // Wait until all threads are finish
    //while (!executor.isTerminated()) {
    //}
    //System.out.println("Finished all threads");
    //All the threads might not be finished at this point of time. Thread endtime purely depends on the time taken by the processing logic inside your thread.
  }
} 
于 2013-02-17T06:55:48.253 に答える
1

このようなことを意味しますか?

class Parallel {
    private ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public void shutdown() {
        pool.shutdown();
    }

    public void foo() {
        pool.submit(new Runnable() {
            @Override
            public void run() {
                // put your code here
            }
        });
    }
}
于 2013-02-17T06:58:10.243 に答える