gpt4 book ai didi

java - 如何避免 Runnable 回调泄漏?

转载 作者:行者123 更新时间:2023-11-30 10:35:20 26 4
gpt4 key购买 nike

下面的代码将在我完成 Activity 时从另一个线程执行回调。那么如何避免 Activity 结束时调用回调或回调中的代码呢?

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

最佳答案

垃圾收集器计算对对象的引用。但是,有几种引用类型。对你有用的是 WeakReference :

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed.

使用构造函数将可运行对象创建为一个类:

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方法实现:

public static void callThread(final Callback listener) {
new Thread(new CallbackRunnable(listener)).start();
}

关于java - 如何避免 Runnable 回调泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41239893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com