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.?
You have to use
this.hostnamein the constructor since you have an argument that is also namedhostname, so if you don’t usethisyou are simply storing the argument’s value in the argument itself.In
runyou don’t have to usethissince there are no other variables with the same name in the scope of the function.See also When should I use "this" in a class? and Java – when to use 'this' keyword