2018年11月13日 星期二

java 閉包 範例

package test_4;

import static java.lang.System.out;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author xman
 */
public class T_2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        int a = 5;

        T2_Closure t = (new T2_Closure<Object, Void>() {
            @Override
            public Void callback(Object in) {

                // 引用 a
                out.printf("callback(%s)\n", a);
                return null;
            }
        });

        t.callback(null);
        //------------------------------------

        T2_Query q = new T2_Query();

        q.query(new T2_Closure<T2_Query, Void>() {
            @Override
            public Void callback(T2_Query in) {

                String res = in.name + " : " + a;
                out.println(res);
                return null;
            }
        });
    }
}
//--------------------------------------
// 閉包

interface T2_Closure<T, E> {

    public E callback(T in);
}

//--------------------------------------

class T2_Query {

    String name = "xyz";

    void query(T2_Closure closure) {

        Thread th = new Thread(() -> {

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                out.println(e);
            }
            closure.callback(T2_Query.this);
        });

        th.start();
      
        out.println("thread start");
    }
}