如何在我的java代码上使用回调方法?

时间:2017-11-19 10:10:35

标签: java interface callback runnable

public class DowloadEngine implements Runnable {

public DowloadEngine(CallBack c) {
    callback = c;
}

public interface CallBack {
    public void processDone(String message);
}

private final CallBack callback;

@Override
public void run() {
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e) {}
    callback.processDone("'CallBack' func is called");
}
}

这里有我的主要课程

public class GUI implements DowloadEngine.CallBack{

public static void main(String[] args){

    Thread thread = new Thread(new DowloadEngine(this));// Error :Make main not static!!
    thread.start();

    //wait a little to see the result
    Scanner scan = new Scanner(System.in);
    scan.nextLine();
    //wait a little to see the result
}

@Override
public void processDone(String message) {
    //code ...
    //code ...
    //code ...
    System.out.println(message);
}
}

我想通过回调方法对主类进行所有工作,但我不理解这些方法。它是如何工作的? 我怎么能一起使用这些?

1 个答案:

答案 0 :(得分:0)

变化:

Thread thread = new Thread(new DowloadEngine(this));

Thread thread = new Thread(new DowloadEngine(new GUI()));