Java异步调方法实例
1、使用接口回调方式,异步线程获取数据
2、定义接口OnCallbackLintener
public interface OnCallbackLintener {
void onCallback(String text);
}
3、定义线程类MyThread,重写run方法进行好事操作,该类拥有一个OnCallbackLintener 的成员变量,并且添加setListener方法
class MyThread extends Thread{
private OnCallbackLsintener listener;
public void setListener(OnCallbackLsintener listener) {
this.listener = listener;
}
@Override
public void run() {
try {
Thread.sleep(5000);
if (null != listener) {
listener.onCallback("The Callback is from myThread");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
自定义一个线程,重写run方法,在线程运行时睡眠5秒,5秒之后通过接口回调的方法,发送了一个字符串"The Callback is from myThread"到回调方法中
4、添加main方法进行测试
class Test {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.setListener(new OnCallbackLsintener() {
@Override
public void onCallback(String text) {
System.out.println(text);
}
});
thread.start();
}}
附上运行截图
