我习惯用类似 JavaScript或类似Erlang的语言编写代码,在那里我可以轻松地创建回调函数.现在我必须用Java写一些东西.我想出了如何执行这样的回调:
import java.util.*;
class Demo extends Thread{
private int data;
public void run(){
ask_for_data(new Runnable(){
public void run(){
on_data();
}
});
}
public void on_data(){
System.out.println("Async callback: " + data);
}
public void ask_for_data(final Runnable callback){
System.out.println("2");
Runnable r = new Runnable(){
public void run(){
data = get_data();
new Thread(callback).start();
}
};
new Thread(r).start();
}
public int get_data(){
try{
Thread.sleep(1000);
} catch (Exception e) {};
return 42;
}
public static void main(String[] args) {
Demo d = new Demo();
d.start();
}
}
问题是:这是正确的方法吗?