I'm new to dealing with multi-threading. I'm confused in one point and seek clarification. I have the following in the main program:
String hostname = null;
ExecutorService threadExecutor = Executors.newFixedThreadPool(10);
MyThread worker = null;
while(resultSet.next()) {
hostname = resultSet.getString("hostName");
worker = new MyThread(hostname);
threadExecutor.execute( worker );
}
threadExecutor.shutdown();
while (!threadExecutor.isTerminated()) {
threadExecutor.awaitTermination(1, TimeUnit.SECONDS);
}
The class that implements runnable is:
public class MyThread implements Runnable{
String hostname=null;
MyThread (String hostname) {
this.hostname=hostname;
System.out.println("New thread created");
}
public void run() {
Class1 Obj1 = new Class1();
try {
obj1.Myfunction(hostname);
} catch (Exception e) {
System.out.println("Got an Exception: "+e.getMessage());
}
}
}
I have a variable called hostname. Everythread needs to get this variable as it must be passed to the function Myfunction
that every thread needs to execute.
I defined a variable called hostname inside the constructor. Then I sent the variable hostname
to MyFunction(hostname).
Since hostname
is defined inside class MyThread
, Then the hostname that it has been sent as an argument to Myfunction
is the thread's hostname.
I don't know if there is a need for me to do the assignment this.hostname=hostname
?? When do I need to write the word this.
? Do I need to send the hostname to Myfunction with the word this.
?