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