有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");
}
}
}
感謝您的回答 – user1822729