线程列表和访问另一个列表

时间:2013-07-19 22:51:48

标签: java arrays multithreading list

几分钟前我已经提出了另一个接近这个问题的问题,并且有很好的答案,但这不是我想要的,所以我试着更清楚一点。

假设我在类中有一个Thread列表:

class Network {

    private List<Thread> tArray = new ArrayList<Thread>();
    private List<ObjectInputStream> input = new ArrayList<ObjectInputStream>();

    private void aMethod() {
        for(int i = 0; i < 10; i++) {
            Runnable r = new Runnable() {
                public void run() {
                    try {
                        String received = (String) input.get(****).readObject(); // I don't know what to put here instead of the ****
                        showReceived(received); // random method in Network class
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                }
            }
            tArray.add(new Thread(r));
            tArray.get(i).start();
        }
    }
}

我应该放什么而不是 * *? tArray列表的第一个线程只能访问输入列表的第一个输入,例如。

编辑:我们假设我的输入列表已经有10个元素

2 个答案:

答案 0 :(得分:0)

如果你放i就可以了。您还需要为每个线程的列表添加ObjectInputStream。我建议您使用input.add来实现此目的。您还需要使用某些线程填充tArray列表,再次使用add。

答案 1 :(得分:0)

以下是解决方案:

private void aMethod() {
    for(int i = 0; i < 10; i++) {
        final int index = i;  // Captures the value of i in a final varialbe.
        Runnable r = new Runnable() {
            public void run() {
                try {
                    String received = input.get(index).readObject().toString(); // Use te final variable to access the list.
                    showReceived(received); // random method in Network class
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
        };
        tArray.add(new Thread(r));
        tArray.get(i).start();
    }
}

如果您希望每个线程从输入数组访问一个元素,您可以使用i变量的值作为列表的索引。直接使用i的问题是内部类不能从封闭范围访问非最终变量。为了解决这个问题,我们将i分配给最终变量index。最终index可通过Runnable的代码访问。

其他修正:

  • readObject().toString()
  • catch(Exception exception)
  • tArray.add(new Thread(r))