Reputation: 73
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
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
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
Reputation: 11484
you can do this:
for(int i = 0; i < clients.length; i++){
new Thread(()->{
clients[i].send(i+"");
}).start();
}
Upvotes: 0