简体   繁体   中英

List of Thread and accessing another list

I've already made another question close to this one several minutes ago, and there were good answers, but it was not what I was looking for, so I tried to be a bit clearer.

Let's say I have a list of Thread in a class :

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();
        }
    }
}

What should I put instead of * * ? The first thread of the tArray list must only access the first input of the input list for example.

EDIT : Let's assume my input list has already 10 elements

It would work if you put i . You also need to add an ObjectInputStream to the list for each thread. I recommend you use input.add for that purpose. You also need to fill the tArray list with some threads, use add again there.

Here's the solution:

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();
    }
}

As you want each thread to access one element from the input array you can use the value of the i variable as an index into the list. The problem with using i directly is that an inner class cannot access non-final variables from the enclosing scope. To overcome this we assign i to a final variable index . Being final index is accessible by the code of your Runnable .

Additional fixes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM