Callable不会作为线程随机打印,但会按常规类顺序打印

时间:2019-02-21 16:44:40

标签: multithreading future executorservice threadpoolexecutor callable

所以我的代码在下面,我的输出是2,4,6,8,10,但是应该是随机的,有帮助吗? 感谢您的宝贵时间。

public class MyCallable implements Callable<Integer> {
  private int i;

  public MyCallable (int i) {
    this.i=i;}

  public Integer call() throws Exception {
    System.out.println("Int iniziale: "+i);
    this.i++;return i;}

  public static void main (String args[]) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(1);

    List<Callable<Integer>> list = new LinkedList<Callable<Integer>>();
    MyCallable callOne= new MyCallable(1);
    MyCallable callTwo= new MyCallable(3);
    MyCallable callThree= new MyCallable(5);
    MyCallable callFour= new MyCallable(7);
    MyCallable callFive= new MyCallable(9);
    list.add(callOne);
    list.add(callTwo);
    list.add(callThree);
    list.add(callFour);
    list.add(callFive);


    System.out.println("Inizializzo l' executor.");
    try {
        List<Future<Integer>> futurelli = executor.invokeAll(list);
        for(Future<Integer> puffo:futurelli) {
            System.out.println(puffo.get());}
    } catch (Exception e) {
        System.out.println("Array in input ad futurelli non riempito");
        e.printStackTrace();
    }
  executor.shutdown();
  }
}

0 个答案:

没有答案