我如何在我的 java 代码上使用回调方法?
How can i use callback method on my java code?
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");
}
}
这里是我的主要class
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);
}
}
我想通过回调方法完成主要 class 上的所有工作,但我不理解这些方法。它是如何工作的?
我怎样才能将它们一起使用?
变化:
Thread thread = new Thread(new DowloadEngine(this));
至
Thread thread = new Thread(new DowloadEngine(new GUI()));
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");
}
}
这里是我的主要class
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);
}
}
我想通过回调方法完成主要 class 上的所有工作,但我不理解这些方法。它是如何工作的? 我怎样才能将它们一起使用?
变化:
Thread thread = new Thread(new DowloadEngine(this));
至
Thread thread = new Thread(new DowloadEngine(new GUI()));