java回调机制,
分享于 点击 31453 次 点评:192
java回调机制,
(与代码无直接关系)原来用到的不多,现在发现这个东西在android请求服务器时贼好用
一个请求工具类,请求用线程发起,返回信息时通过回调函数将数据返回给activity
写法记录:
public interface CallBackInterface {
void callBack(String str);
}
/** 类似activity */
public class Print implements CallBackInterface {
public Print(){
new TestThread(this);
System.out.println("我写在调用线程后面");
}
/** 实现接口 */
public void callBack(String str){
System.out.println(str);
}
}
/** 类似请求类 */
public class TestThread {
public TestThread(CallBackInterface cbi){
Thread thread = new Thread(){
@Override
public void run(){
try {
sleep(2000);
String str = "hello, 线程快跑完了";
cbi.callBack(str);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
}
public class Main{
public static void main(String[] args) {
new Print();
}
}
相关文章
- 暂无相关文章
用户点评