I'm used to write code in JavaScript-like or Erlang-like languages, where I can make callback functions in easy way. Now I have to write something in Java. I figured it out how to perform callback like this:
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();
}
}
Question is: is it correct approach?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With