我遵循了教程(here)
但是我不明白。据我所知,回调是将在主线程完成后调用的东西。我尝试运行该示例,但这不是我所理解的。
这些是我的课程:
InterestingEvent.java
package callback;
public interface InterestingEvent {
// This is just a regular method so it can return something or
// take arguments if you like.
public void interestingEvent ();
}
CallMe.java
package callback;
public class CallMe implements InterestingEvent {
private EventNotifier en;
public CallMe ()
{
// Create the event notifier and pass ourself to it.
en = new EventNotifier (this);
}
// Define the actual handler for the event.
public void interestingEvent ()
{
// Wow! Something really interesting must have occurred!
// Do something...
System.out.println("Interesting event method");
}
}
EventNotifier.java
package callback;
public class EventNotifier {
private InterestingEvent ie;
private boolean somethingHappened;
public EventNotifier (InterestingEvent event)
{
// Save the event object for later use.
ie = event;
// Nothing to report yet.
somethingHappened = true;
}
public void doWork ()
{
System.out.println("doWork 1");
// Check the predicate, which is set elsewhere.
if (somethingHappened)
{
System.out.println("doWork 2");
// Signal the even by invoking the interface's method.
ie.interestingEvent ();
System.out.println("doWork 3");
}
}
public static void main(String[] args) {
InterestingEvent ie = new CallMe();
EventNotifier e = new EventNotifier(ie);
e.doWork();
System.out.println("Main flow finish!");
}
}
输出:
doWork 1
doWork 2
Interesting event method
doWork 3
Main flow finish!
主线程在程序结尾处完成。
据我所知,输出应为:
Main flow finish! -- Main thread should be done first!!!
doWork 1
doWork 2
Interesting event method
doWork 3
请任何人解释该示例,什么不正确?
谢谢!