2017-12-18 7 views
2

リスト内に値を挿入する2つのタスクを作成しました。Java Concurrency - 誰でも出力を助けることができます。なぜリストは空ですか?

実行者サービスを使用してこれらのタスクを実行します。

最後に、これらのリスト内の値を調べてみます。

実行者サービスがシャットダウンされると、値がリストに挿入されないのはなぜですか?

この現象の背後にある理由を特定できない場合は、これを説明できます。

package com.executors; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.List; 
import java.util.concurrent.Callable; 
import java.util.concurrent.ExecutionException; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.Future; 
import java.util.concurrent.atomic.AtomicInteger; 

public class ExecutorTesting { 

public static AtomicInteger counter = new AtomicInteger(0); 
static List<employee> list = new ArrayList<employee>(); 

public static void main(String[] args) throws InterruptedException, ExecutionException { 

    list = Collections.synchronizedList(list); 

    Callable<List<employee>> c1 = new Callable<List<employee>>() { 

     @Override 
     public List<employee> call() throws Exception { 
      for (int i = 0; i < 10; i++) { 
       list.add(new employee("varun", ExecutorTesting.counter.incrementAndGet())); 
      } 
      return list; 
     } 
    }; 

    Callable<List<employee>> c2 = new Callable<List<employee>>() { 

     @Override 
     public List<employee> call() throws Exception { 
      for (int i = 0; i < 10; i++) { 
       list.add(new employee("varun", ExecutorTesting.counter.incrementAndGet())); 
      } 
      return list; 
     } 
    }; 

    ExecutorService es = Executors.newFixedThreadPool(2); 

    try { 
     Future<List<employee>> ef1 = es.submit(c1); 
     Future<List<employee>> ef2 = es.submit(c2); 

     if (ef1.isDone()) { 
      System.out.println("first value : " + ef1.get()); 
     } 
     if (ef2.isDone()) { 
      System.out.println("first value : " + ef2.get()); 
     } 

     System.out.println(list); 

    } finally { 
     es.shutdown(); 
    } 

} 

} 

class employee { 
String name; 
int id; 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public int getId() { 
    return id; 
} 

public void setId(int id) { 
    this.id = id; 
} 

public employee(String name, int id) { 
    super(); 
    this.name = name; 
    this.id = id; 
} 

public String toString() { 
    return this.name + " : " + this.id; 
} 

} 
+0

いいえ悪い、私は両方のタスクを提出したい –

+0

このコードは、オーブンでディナーをポップし、30秒後にそれが終了したかどうかを確認してから、オーブンはそこに食事を残す。一方、 'get'を呼び出すことは、オーブンから引き出す前に夕食を調理するまで待つことと同じです。 –

+0

それを得ることができない、私は将来のオブジェクト –

答えて

1

あなたはExecuterServiceに提出した直後future.isDone()を呼んでいます。ほとんどの場合、実行は開始されていませんが、完了することはありません。したがって、isDoneの呼び出しはすべてfalseに戻り、すべてを完了するだけです。

私はあなたが直面している具体的なシナリオについてはよく分からないが、この特定のテストコードで問題を解決するために、あなただけの各Futuregetを呼び出す必要があります:

System.out.println("first value : " + ef1.get(10, TimeUnit.SECONDS)); 
System.out.println("first value : " + ef2.get(10, TimeUnit.SECONDS)); 

私はあなたのコピーを残しました&あなたの出力テキストのペーストエラー;-)

関連する問題