我是多线程编程的新手。该代码不执行我想要的操作:

public class Test {
    static int i;
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(10);
        for(i = 0; i<10 ;i++) {
             executor.execute(new Runnable() {
                 public void run () {
                     System.out.println(i);
                 }
            });
        }
    }
}


输出:
2
4
3
4
2
6
6
8
9
10

我希望它可以输出诸如0、1、2、3、4、5、6、7、8、9之类的有序或无序的东西。
我的问题是我该怎么做才能获得预期的输出,以及如何使它们井然有序。

提前致谢

最佳答案

您可以拥有一个实现Runnable的类,并使用构造函数将静态字段复制到实例字段中:

executor.execute(new MyRunnable(i));


class MyRunnable implements Runnable {
     int i;

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

     // run method
 }


这保证了每个线程在i循环中具有与for完全相同顺序的唯一整数。

07-24 09:46
查看更多