Re: how to pass parameters to java threads
You can write a new constructor for the thread that takes the number as
a parameter or write a method like setNumber(int number), obviously this
method should be called before calling start()
laclac01@gmail.com wrote:
am trying to learn java, and i have a question. How do i pass
parameters to threads??? Here is an example;
import java.io.*;
import java.net.*;
public class MultiEchoServer {
public static int MYECHOPORT = 8189;
public static void main(String argv[]) {
ServerSocket s = null;
int myNumber =8;
try {
s = new ServerSocket(MYECHOPORT);
} catch(IOException e) {
System.out.println(e);
System.exit(1);
}
while (true) {
Socket incoming = null;
try {
incoming = s.accept();
} catch(IOException e) {
System.out.println(e);
continue;
}
new SocketHandler(incoming).start();
}
}
}
class SocketHandler extends Thread {
Socket incoming;
SocketHandler(Socket incoming) {
this.incoming = incoming;
}
public void run() {
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(
incoming.getInputStream()));
PrintStream out =
new PrintStream(incoming.getOutputStream());
out.println("Hello. Enter BYE to exit");
boolean done = false;
while ( ! done) {
String str = reader.readLine();
if (str == null)
done = true;
else {
out.println("Echo: " + str);
if (str.trim().equals("BYE"))
done = true;
}
}
incoming.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
How would i pass "myNumber" to the thread. I know from looking up on
the internet that run() does'nt take parameters. It would be great if i
could just do run(int myNumber); But alas i can't. mynumber is a number
that will be changed or accessed by each thread
This is just an example, as I want to apply to my own code.