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());
            });
        }
    }
}

点墨
26 声望3 粉丝

全栈前端开发工程师