2

我正在CreateOneNon-Activity类中调用一个方法,并且方法需要在执行后CreateOne返回一个。所以我在调用任务后添加了以下行。ObjectTask

task.wait();

但它返回错误,如

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);
}

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

为什么会抛出错误?

有任何想法吗?

4

1 回答 1

1

这是关于类似问题的问题可能有用

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

引用:“这是等待和通知的使用方式:”

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);
}
于 2017-11-19T11:25:46.857 回答