2018年11月10日 星期六
java 非同步呼叫 callback
public class Ajax_1 {
Callback callback;
String name;
void query(Callback callback) {
this.callback = callback;
// 非同步
Thread t = new Thread(() -> {
// 取得查詢
String name = (new SyncSqlQuery()).query();
Ajax_1.this.name = name;
Ajax_1.this.callback.callback();
});
t.start();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Ajax_1 a = new Ajax_1();
int x = 5;
a.query(() -> {
// 及時命令
out.println(a.name);
});
a.query(new Callback(){
public void callback(){
// 及時命令
out.println(a.name);
}
});
}
}
//-------------------------------------------------------
public interface Callback {
void callback();
}
//-------------------------------------------------------
public class SyncSqlQuery {
public static int id = 0;
String query(){
return "SyncSqlQuery_" + id++;
}
}
//////////////////////////////////////////////////////////////////////////
/**
*
* @author xman
*/
public class Ajax_1 {
String name;
void query(Callback callback) {
Thread t = new Thread(() -> {
// 取得查詢
String name = (new SyncSqlQuery()).query();
Ajax_1.this.name = name;
});
t.start();
try {
t.join();
} catch (InterruptedException ex) {
out.println(ex);
}
callback.callback();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Ajax_1 a = new Ajax_1();
int x = 5;
a.query(() -> {
out.println(a.name);
});
a.query(new Callback(){
public void callback(){
out.println(a.name);
}
});
}
}