在Java中与Runnable接口实现回调 [英] Implementing callbacks in Java with Runnable

查看:882
本文介绍了在Java中与Runnable接口实现回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经习惯了使用JavaScript编写状或二郎神般的语言,在这里我可以回调函数简单的方法code。现在,我必须用Java编写的东西。我想通了如何执行回调是这样的:

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?

推荐答案

只是一个接口(回调实现)传递给您的可运行这样

simply pass an interface (callback implementation) to your runnable like this

interface Callback {
    void callback(); // would be in any signature
}

class MyThread implements Runnable {

    Callback c; 

    public MyThread(Callback c) {
        this.c = c;
    }

    public void run() {
        // some work
        this.c.callback(); // callback
    }
}

和一切简单的教程,您需要了解线程这里

and a simple tutorial about everything you need about thread here

这篇关于在Java中与Runnable接口实现回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆