美文网首页
在Java中与Runnable接口实现回调(Implementi

在Java中与Runnable接口实现回调(Implementi

作者: whiteleaf | 来源:发表于2019-08-21 11:00 被阅读0次
    import java.util.*;
    
    class Demo extends Thread{
    
        private int data;
    
        public void run(){
            ask_for_data(new Runnable(){
                public void run(){
                    on_data();
                }
            });
        }
    
        public void on_data(){
            System.out.println("Async callback: " + data);
        }
    
        public void ask_for_data(final Runnable callback){
            System.out.println("2");
            Runnable r = new Runnable(){
                public void run(){
                    data = get_data();
                    new Thread(callback).start();
                }
            };
            new Thread(r).start();
        }
    
        public int get_data(){
            try{
                Thread.sleep(1000);
            } catch (Exception e) {};
            return 42;
        }
    
        public static void main(String[] args) {
            Demo d = new Demo();
            d.start();
        }
    }
    

    simply pass an interface (callback implementation) to your runnable like this

    interface Callback {
        void callback(); // would be in any signature
    }
    
    class MyThread implements Runnable {
    
        Callback c; 
    
        public MyThread(Callback c) {
            this.c = c;
        }
    
        public void run() {
            // some work
            this.c.callback(); // callback
        }
    }
    

    相关文章

      网友评论

          本文标题:在Java中与Runnable接口实现回调(Implementi

          本文链接:https://www.haomeiwen.com/subject/olkvjctx.html