如何确保任务只有在前一个异步任务完成执行后才开始执行? [英] How to make sure a task starts its execution only after a previous asynchronous task has completed its execution?

查看:214
本文介绍了如何确保任务只有在前一个异步任务完成执行后才开始执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个任务 - task1() task2() task1()从网上获取一个值,并添加一个名为 num的 int 变量 task1() task2() num C>。 task2()应该打印变量 num 的值。

但是这里的问题是,在从网上获取值之前, num 变量被打印出来。

  int num = 0; 
public static void main(String [] args)
{
task1();
task2();


public static void task1()
{
int fetchedValue;
rootRef.addListenerForSingleValueEvent(new ValueEventListener(){
$ b $ public void onDataChange(DataSnapshot snapshot){
fetchedValue = Integer.parseInt(snapshot.getValue()。toString());
num = num + fetchedValue;
}

public void onCancelled(FirebaseError arg0){
System.out.println(cancelled);
}
});
num = num + fetchedValue;


$ b public static void task2()
{
System.out.println(Updated number:+ num);


解决方案

确定是否已经获取了该值。

这个布尔值可以从两个任务中访问。如果task1已经完成抓取,task1会将布尔值更改为 true 。 task2在循环中检查提取是否已完成,如果已提取 num ,则打印 num 。 $ b

I have two tasks - task1() and task2(). task1() fetches a value from the internet and adds it with a int variable named num. Variable num is accessible to both task1() and task2(). task2() is just supposed to print the value of variable num.

But the problem here is that before the value is fetched from the internet ,the num variable gets printed.

int num = 0;
public static void main(String[] args)
{
     task1();
     task2();
}

public static void task1()
{
    int fetchedValue;
    rootRef.addListenerForSingleValueEvent(new ValueEventListener() {

        public void onDataChange(DataSnapshot snapshot) {
            fetchedValue = Integer.parseInt(snapshot.getValue().toString());
            num = num + fetchedValue ;
        }

        public void onCancelled(FirebaseError arg0) {
            System.out.println("cancelled");
        }
    });
    num = num + fetchedValue;

}

public static void task2()
{
    System.out.println("Updated number : "+num);
}

解决方案

You could use a boolean to determine if the value has been fetched.

This boolean is accessible from both tasks. task1 changes boolean to true if it has completed fetching. task2 checks in a loop whether fetching has finished and prints num if num has been fetched.

这篇关于如何确保任务只有在前一个异步任务完成执行后才开始执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆