我正在尝试同步一个Android应用程序的两块代码。
第一个块使用AsyncFacebookRunner来请求用户的兴趣(如果有的话)。
如果找到兴趣,用户的成员变量就会从Facebook响应中填充他们的兴趣。
第二个代码块通过查看该成员变量来检查用户是否真正感兴趣。如果有兴趣,将执行几行额外的代码。
synchronized(this)
{
if ( (friend.getmActivities().length() == 0) && (friend.getmInterests().length() == 0) )
friend.requestInterests(mFacebook); // Get that friend's Facebook activities and interests.
}
synchronized(this)
{
if ( (friend.getmActivities().length() == 0) && (friend.getmInterests().length() == 0) )
{
final AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
alertDialog.setTitle("Sorry...");
alertDialog.setMessage("Your friend isn't sharing their interests.");
alertDialog.setButton("Go Back", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
}我希望第二个块在执行之前等待friend.requestInterests()完成。
编辑:最后,我重新构造了代码,以利用runner的onComplete方法。这一切都是当我修改我的程序的结构,并必须改变一切。谢谢大家的帮助。。
发布于 2011-05-18 22:54:15
,我希望第二个块在执行之前等待friend.requestInterests()完成。
JVM确保这两个块不会在相同的实例中同时执行。
如果您还想确保第二个块只在第一个块运行之后才能运行,那么您可以使用一个状态变量和wait / notify调用来完成这个任务。但是更好的方法是使用同步类中的一个,如CountDownLatch;
private CountDownLatch latch = new CountDownLatch(1);
...
synchronized(this) {
// do first actions
}
this.latch.countdown();
....
this.latch.await();
synchronized(this) {
// do second
}实际上,如果这些地方是访问和更新相关对象状态的唯一位置,那么您应该能够免除synchronized块。对countdown和await的调用将提供必要的“先于”关系,以确保正确的同步。
然而,@pst的评论提出了这样一个观点:使用您的代码使用的Facebook库框架的API,可能有更好的方法来实现这一点。
https://stackoverflow.com/questions/6051768
复制相似问题