如何避免Runnable回调泄漏?

时间:2016-12-20 10:17:12

标签: java android multithreading reference weak-references

我有以下代码,当我完成活动时,它会执行另一个线程的回调。那么如何避免在活动结束时调用回调或回调中的代码

public static interface Callback{
    public void onCallback();
}

class ActivityA {
    TextView tv = ...;
    Handler handler = ...;
    public void onClick(View v) {
        Business.callThread(new Callback() {

            @Override
            public void onCallback() {
                handler.post(new Runnable(){
                    public void run(){
                        tv.setText("xxxx");
                    }
                });
            }
        });
    }
}

class Business {
    public static void callThread(final Callback listener) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(5000); //sleep 5s;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                listener.onCallback();
            }
        }).start();
    }
}

1 个答案:

答案 0 :(得分:1)

垃圾收集器计算对象的引用。但是,有几种参考类型。您的案例有用WeakReference

  

弱引用对象,它们不会阻止它们的指示物被最终化,最终化,然后回收。

使用构造函数创建runnable作为类:

  MySubClass subClass=new MySubClass();
  MySubClass subClass2=(MySubClass)subClass.filterOn("Hello World");

然后调用监听器:

static class CallbackRunnable implements Runnable {
    WeakReference<Callback> listener;

    public CallbackRunnable(Callback listener) {
        this.listener = new WeakReference<Callback>(listener);
    }

    @Override
    public void run() {
        try {
            Thread.sleep(5000); //sleep 5s;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (listener.get() == null) {
            return;
        }
        listener.get().onCallback();
    }
}

if (listener.get() == null) { return; } listener.get().onCallback(); 方法实现:

callThread