There are 3 classes.
CallMe
The basic class which prints the messageCaller
Implements Runnable
and it gets the object from the main class Synch
Synch
The main class which creates the object for CallMe
and passes the same to class Caller
class and starts the thread.Question:
In the Synch
class, what is the need to pass the object to the class Caller
? When I tried a call to the class Caller
without the object of CallMe
the compiler throws a NullPointerException
. Could you please provide any reasons for this behaviour.
eg : Caller ob1 = new Caller("Hello"); // calling without an object of class "CallMe"
Below is the working code for reference.
public class CallMe {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
CallMe target;
Thread t;
public Caller(CallMe targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run() {
target.call(msg);
}
}
class Synch {
public static void main(String args[]) {
CallMe target = new CallMe();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
}
The compiler throws a NullPointerException because of the line
target.call(msg)
If you pass null to the Caller constructor, then the instance variable target gets set to null, and you're calling a method on a null reference, hence NullPointerException.
As for why you need to have both a 'Caller' and a 'CallMe' class, it's just a matter of style. The idea is to create a Runnable 'wrapper class' for whatever business logic your code may include. That way threading is not tied into the core of your project.