在非 Activity 上的 Android 应用程序中等待之前对象未被线程锁定

Object not locked by thread before wait in Android app on Non Activity

我正在从 Non-Activity class 调用方法 CreateOne 并且 CreateOne 方法需要 return Object 在 [=20] 之后=] 执行。所以我在调用任务后添加了以下行。

task.wait();

但它是 returning 错误,如

object not locked by thread before wait()

这是我的完整代码:

public class MyStitchHelper
{
    public Object CreateOne(Map<String, Object> map) throws InterruptedException
    {
        Object returnObject = null;
        Document mapDoc = new Document(map);
        ArrayList<Document> list = new ArrayList<>();

        list.add(mapDoc);

        Document itemsDocument = new Document("items", list);
        PipelineStage itemsStage = new PipelineStage("literal", "", itemsDocument);
        Document AuthDocument = new Document();
        AuthDocument.append("database","my_db");
        AuthDocument.append("collection", _collectionName);
        PipelineStage AuthStage = new PipelineStage("insert", "mongodb-atlas", AuthDocument);


        Task<List<Object>> task = _client.executePipeline(itemsStage, AuthStage);

        task.wait();

        if(task.isSuccessful())
        {
            Log.e("UserDAL", task.getResult().toString());
            returnObject = task.getResult();
        }
        else
        {
            Log.e("UserDAL", "Error Adding Collectionsss");
            task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e("UserDAL", "" + e.getMessage());
            }
            });
        }

        return returnObject;
    }
}

调用方式:

public void AddUser()
{
    MyStitchHelper DBHelper = new MyStitchHelper();

    Map<String, Object> map = new HashMap<>();

        map.put(User.Columns.EMAIL,user.get_userName());
        map.put(User.Columns.PASSWORD, user.get_password());
        map.put(User.BaseColumns.CREATED_DATE, Calendar.getInstance().getTime());

        Document doc = (Document) DBHelper.CreateOne(map);
}

首先,我正在尝试做的实现是否正确只是创建一个新用户并在创建后 returning 文档对象。

为什么会抛出错误?

有什么想法吗?

这里 Question 关于类似的问题。可能有用

简而言之,来自最佳答案:

引用:"Here's how wait and notify were meant to be used:"

private Queue<Product> q = ...;
private Object lock = new Object();

void produceSomething(...) {
    Product p = reallyProduceSomething();
    synchronized(lock) {
        q.add(p);
        lock.notify();
    }
}

void consumeSomething(...) {
    Product p = null;
    synchronized(lock) {
        while (q.peek() == null) {
            lock.wait();
        }
        p = q.remove();
    }
    reallyConsume(p);
}