2

新しいスレッドで次のコードを実行するために、内部メソッドを実装しようとしています

MyPojo result = null;
final MyPojo result2 = result;

FutureTask<MyPojo> runnableTask = new FutureTask<MyPojo>(
    new Runnable() {  

        BindJSON<MyPojo> binding;

        // Make the URL at which the product list is found
        String sourceURLString = 
            "http://www.....ca/files/{CAT_ID}.json";                

        @Override
        public void run() {  
            sourceURLString = sourceURLString.replace("{CAT_ID}", catId);
            binding = new BindJSON<MyPojo>();  
            result2 = binding.downloadData(sourceURLString, MyPojo.class);  
        }  
    }, 
    result2);

runnableTask.run();

そこで、次のようなエラーが発生します。最後のローカル変数result2は、囲んでいる型で定義されているため、割り当てることができません。私はこの答えを見てみます:別のメソッドで定義された内部クラス内の非最終変数iを参照することはできませんが、それは私にとっては機能しませんでした。これを機能させるにはどうすればよいですか?

4

2 に答える 2

4

Callableではなく、を使用したい場合がありますRunnable

// the variable holding the result of a computation
String result = null;

FutureTask<String> runnableTask = new FutureTask<String>(
        new Callable<String>() {
            public String call() throws Exception {
                // (asynchronous) computation ...
                return "42";
            }
        });

System.out.println("result=" + result); // result=null

// this will invoke call, but it will all happen in the *same thread*
runnableTask.run();

// to have a parallel thread execute in the 'background'
// you can use java.util.concurrent.Executors
// Note: an ExecutorService should be .shutdown() properly
// Executors.newSingleThreadExecutor().submit(runnableTask);

// waits for the result to be available
result = runnableTask.get();

// you can also add timeouts:
// result = runnableTask.get(100, TimeUnit.MILLISECONDS);

System.out.println("result=" + result); // result=42
于 2012-12-12T13:53:08.977 に答える
3

同じスレッドで実行するため、FutureTask の使用はあまり役に立ちません。エグゼキューターを使用して呼び出し可能オブジェクトを送信し、目的を達成できます。

    ExecutorService executor = Executors.newFixedThreadPool(1);

    Callable<MyPojo> task = new Callable<MyPojo> () {
        BindJSON<MyPojo> binding;
        // Make the URL at which the product list is found
        String sourceURLString = "http://www.....ca/files/{CAT_ID}.json";

        @Override
        public MyPojo call() {
            sourceURLString = sourceURLString.replace("{CAT_ID}", catId);
            binding = new BindJSON<MyPojo>();
            return binding.downloadData(sourceURLString, MyPojo.class);
        }
    };

    Future<MyPojo> future = executor.submit(task);
    MyPojo result = future.get();

注: への呼び出しはfuture.get();、タスクが完了するまでブロックされます。

于 2012-12-12T13:52:51.303 に答える