我正在尝试使用单例的 Handler.post() 方法从另一个可运行对象运行可运行对象,但是直到原始可运行对象完成后,第二个可运行对象才会运行。在下面的示例代码中,我从应用程序中的某个位置调用 MyManager,getInstance().startCommand() 。 MyCommand 类中的 myRun 变量在线程上设置了 sleep ,因此我可以测试超时功能,但名为 mTimeoutTimer 的可运行对象只有在 myRun 可运行对象完成之后才会执行。为什么会发生这种情况,我该如何改变?
public class MyManager{
private MyManager sInstance;
private Handler mHandler;
private Runnable mTimeoutTimer;
public static MyManager getInstance(){
if(sInstance == null){
sInstance = new MyManager();
}
return sInstance;
}
private MyManager(){
mHandler = new Handler();
mTimeoutTimer = new Runnable() {
@Override
public void run() {
Log.e(“RUNNABLE RUNNING!”);
}
};
public class MyCommand {
private Runnable myRun;
public MyCommand(){
myRun = new Runnable() {
@Override
public void run() {
MyManager.getInstance().startTimeoutTimer();
try {
Thread.sleep(COMMAND_TIMEOUT_MILLIS * 3);
} catch (InterruptedException e) {}
MyCommand.this.execute();
}
};
}
public void execute() {
myRun.run();
}
}
private void startTimeoutTimer(){
mHandler.postDelayed(mTimeoutTimer);
}
public void startCommand(){
new MyCommand().execute();
}
}
最佳答案
这是因为 Handler 是在主线程中调用的,所以它会等待另一个 Handler 完成
而是将您的其他处理程序放入 HandlerThread
中,以便在单独的线程上运行您的处理程序
HandlerThread thread = new HandlerThread("HandlerThread");
thread.start();
Handler handler = new Handler(thread.getLooper());
HandlerThread 的文档
Handy class for starting a new thread that has a looper.
The looper can then be used to create handler classes.
Note that start() must still be called.
关于android - 发布在另一个可运行的可运行未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24172356/