merpi
merpi

Reputation: 73

How to create threads in a loop, in an anonymous class referring to the loop variable?

I'm doing a concurrent server program and I'm testing it. Into a JUnit Test I'm typing this:

[...]

Client[] clients = new Client[30];
for ( int i = 0; i<30 ; i++){
    clients[i] = new Client("localhost", SERVPORT);
}

for ( Integer i = 0; i<30 ; i++){
    new Thread(){
        public void run(){
            clients[i].send(i.toString()); <--
        }
    }.start();
}
[...]

The problem is that Java doesn't compile because I cannot refer to a non-final variable i inside an inner class defined in a different method, so I have to modify and write i as final (but I shouldn't). I understand that, but... How can I send messages from all the clients concurrently?

Additional information: In the method send(String), I send a message to the server and wait until the server responds.

Upvotes: 1

Views: 460

Answers (3)

M A
M A

Reputation: 72884

You can run the thread from within the original for loop, skipping the use of the index variable i by referencing a local variable instead:

final Client[] clients = new Client[30];
for (int i = 0; i < 30; i++) {
    final Integer integer = new Integer(i);
    final Client client = new Client("localhost", SERVPORT);
    clients[i] = client;
    new Thread(){
        public void run(){
            client.send(integer.toString());
        }
    }.start();
}

Note the final Integer created for each loop.

Upvotes: 2

Jamie
Jamie

Reputation: 1937

You can define your own thread class that accepts a Client parameter in the constructor.

class MyThread extends Thread
{
    private Client client;
    private String message;
    MyThread(Client client, String message)
    {
        this->client = client;
        this->message = message;
    }
    public void run()
    {
        client.send(message);
    }
}

Upvotes: 0

satnam
satnam

Reputation: 11484

you can do this:

for(int i = 0; i < clients.length; i++){
  new Thread(()->{
     clients[i].send(i+"");
  }).start();
}

Upvotes: 0

Related Questions