有3个班。
CallMe打印消息的基本类Caller实现Runnable并从主类获取对象SynchSynch为类创建对象CallMe并将其传递给Caller类并启动线程的主类。
问题:在Synch类中,需要将对象传递给类Caller吗?当我尝试在没有编译器Caller对象的情况下调用类时会抛出. 您能否提供这种行为的任何原因。CallMeNullPointerException
例如:Caller ob1 = new Caller("Hello"); // calling without an object of class "CallMe"
以下是供参考的工作代码。
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");
}
}
}