AndroidAnnotations——Fork join

Fork join

Since AndroidAnnotations 1.0

Fork / Join for the poor Android dev

Let's say you want to split a background operation into two separate operations that run concurrently, and then do something on the UI thread when both are done.假设你想将一个后台操作分成单独的两部分,并且需要同时运行,然后两部分都完成时在UI线程更新。

Here is a simple way to implement this, thanks to @Background and @UiThread.这里有一个简单的方法来实现,感谢 @Background 和@UiThread。

@EActivity
public class MyActivity extends Activity {

  // Instances should only be accessed from the UI Thread to guarantee thread safety
  static class ResultHolder {
    ResultA resultA;
    ResultB resultB;
  } 
 
  // Multiple clicks will start multiple distinguished computations
  @Click(R.id.myButton)
  void startForkableComputation() {
    ResultHolder resultHolder = new ResultHolder();
    computeResultA(resultHolder);
    computeResultB(resultHolder);
  }

  @Background
  void computeResultA(ResultHolder resultHolder) {
    ResultA resultA = new ResultA();
    // Do some stuff with resultA
    joinWork(resultHolder, resultA, null);
  }

  @Background
  void computeResultB(ResultHolder resultHolder) {
    ResultB resultB = new ResultB();
    // Do some stuff with resultB
    joinWork(resultHolder, null, resultB);
  }

  @UiThread
  void joinWork(ResultHolder resultHolder, ResultA resultA, ResultB resultB) {
    if (resultA != null)
      resultHolder.resultA = resultA;
    if (resultB != null)
      resultHolder.resultB = resultB;

    if (resultHolder.resultA == null || resultHolder.resultB == null) {
      return;
    }

    // Show the results on the UI Thread
  }

}

This works because we are joining the work in the Ui Thread, which is always the same thread. We also ensure that we always access ResultHolder from the Ui Thread.合并工作总是在UI线程中进行,我们保证时刻访问 ResultHolder 

Note by  @pyricau: although I'm quite sure everything here is right and safe, I just received Java Concurrency in Practice from Amazon, so I'll read it with this  fork / join use case in mind!
Note by  @pyricau:最然我很确信万事OK,但我刚刚收到来自Amazon的 Java Concurrency in Practice ,所以我会带着   fork / join 这个例子读这本书。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值