-4

私は Java ウィンドウ アプリケーションを初めて使用します。スクリプトを実行する Java ツールを作成する必要があります。スクリプトは次のよう- .txt fileに実行され、次の出力が得られます。

line 1   
line 2  
line 3
and so on....  

次の手順を実行するには、Java プログラムが必要です。

  1. 各行の構文が正しいかどうかを確認してください
  2. 行が正しい場合、この行で byte[] を作成します
  3. byte[] 配列を処理する

ここでスレッドの概念を使用したいと思います。子スレッドが 1 と 2 のプロセスを処理し、abyte[]をメイン スレッドに返すようにします。メイン プログラムは、このバイト配列を処理します。

スレッドを使用できますが、戻り値に問題があります。byte[]各行のスレッドはどのようにメインスレッドに戻りますか? byte[]メインスレッドはこの配列を同期してどのように受け取りますか?

4

1 に答える 1

0

スレッドから値を返す最も簡単な方法は、ExecutorServiceおよびFutureクラスを使用することです。スレッドプールには、必要な数のジョブを送信できます。スレッドを追加したり、ジョブごとにスレッドをフォークしたりすることもできます。の他の方法を参照してくださいExecutors

例えば:

// create a thread pool
ExecutorService threadPool = Executors.newFixedThreadPool(2);
// submit a job to the thread pool maybe with the script name to run
Future<byte[]> future1 = threadPool.submit(new MyCallable("scriptFile1.txt"));
// waits for the task to finish, get the result from the job, this may throw
byte[] result = future1.get();

public class MyCallable implements Callable<byte[]> {
    private String fileName;
    public MyCallable(String fileName) {
        this.fileName = fileName;
    }
    public byte[] call() {
        // run the script
        // process the results into the byte array
        return someByteArray;
    }
});
于 2012-05-09T17:34:53.743 に答える