关于java:java-lambda表达式-回调函数

41次阅读

共计 1101 个字符,预计需要花费 3 分钟才能阅读完成。

java 应用 lambda 表达式做回调函数, 定义一个 interface 写一个办法即可(如果一个接口只有一个形象办法(包含继承的),该接口是一个函数接口,函数接口能够应用 lambda 表达式实现),lambda 表达式函数外部能够获取内部变量,会保留堆栈信息

源码

Callback.java

public interface Callback{void onCompletion();
}

Test.java

public class Test implements Runnable {BlockingDeque<Callback> queue = new LinkedBlockingDeque<>();

    void init(){Thread thread = new Thread(this,"Test");
        thread.start();}

    void sendAsync(Callback callback){queue.add(callback);
    }

    @Override
    public void run() {while (true){
            try {Thread.sleep(10);
                Callback callback = queue.take();
                callback.onCompletion();} catch (InterruptedException e) {e.printStackTrace();
            }

        }
    }
}

TestObject.java

public class TestObject {public String getVal() {return val;}

    public void setVal(String val) {this.val = val;}

    private String val;


}

Main.java

public class Main {public static void main(String[] args) {Test test = new Test();
        test.init();

        for(int i=0;i<10;i++){
            String data = "i=" + i;
            TestObject obj = new TestObject();
            obj.setVal(data);
            System.out.println("handle before" + obj + obj.getVal());
            System.out.println(Thread.currentThread().getName());
            test.sendAsync(()->{System.out.println("handle"+obj + obj.getVal());
                System.out.println(Thread.currentThread().getName());
            });
        }
    }
}

正文完
 0