【问题标题】:ScheduledThreadPoolExecutor Callable() blocking my main Activity UI threadScheduledThreadPoolExecutor Callable() 阻塞了我的主 Activity UI 线程
【发布时间】:2013-09-13 06:52:26
【问题描述】:

如果 Callable() ScheduledThreadPoolExecutor 应该在像 Runnable() 这样的后台线程中运行,那么它为什么会阻塞我的 UI 线程?

我认为应该像 Runnable 那样在后台线程中运行。

 ScheduledThreadPoolExecutor stpe;

onCreate 内部

  ScheduledFuture<Integer> sf = stpe.schedule(new OtherObject2(), 5, TimeUnit.SECONDS);

  try {
    int returnedInteger = sf.get();
    textViewThree.setText("the returned integer is: " + returnedInteger);
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

嵌套内部类

 public class OtherObject2 implements Callable<Integer> {

@Override
public Integer call() throws Exception {

    Integer integerReturn = 23;

    return integerReturn;
} 

 }

【问题讨论】:

    标签: java android multithreading concurrency


    【解决方案1】:

    以下行int returnedInteger = sf.get(); 阻塞等待结果。

    【讨论】:

    • 我是否必须从 onCreate 内部启动一个新线程才能将这一行放入该新线程中。避免这个问题?
    • 怎么办?我只想让 textView 在从可调用对象中获取整数时显示整数
    • 从任务中调用 SwingUtilities.invokeLater(),使用 Runnable 更新 UI,一旦结果已知。
    【解决方案2】:

    运行一个特殊的 UI 任务,而不是 OtherObject2 中的 return integerReturn

    final Integer integerReturn = 23;
    runOnUiThread(new Runnable() {
        public void run() {
           textViewThree.setText("the returned integer is: " + integerReturn);
        }
    });
    

    OtherObject2不需要实现Callable,Runnable就够了。通过schedule()提交OtherObject2没用,execute()就可以了。

    【讨论】:

    • 确实如此,但在这种情况下,最好使用 Runnable。因为你没有从 Callable 返回任何东西。 Callable 和 Runnable 之间的区别在于,在 Callable 中你可以返回一些东西。如果我要使用 runOnUiThread,那么如果您在不阻塞 UI 线程的情况下无法返回任何内容,那么在 Callable 中返回语句的目的是什么?
    • 是的it would be better to use Runnable,所以我说:Runnable is enough
    猜你喜欢
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 2019-09-01
    • 2019-07-01
    • 2013-05-03
    • 1970-01-01
    相关资源
    最近更新 更多