编写和线程之间的阅读与Android境界 [英] Writing and reading between threads with Android Realm

查看:189
本文介绍了编写和线程之间的阅读与Android境界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我执行服务器线程和遇到的问题的一些调查。

I'm performing some investigation of Realm threading and encountered issue.

在这个简单的例子我有2 的对象,一个是写作和第二个阅读。读者获取数书写的对象始终为0,但里面的作家范围尺寸()在DB项目是正确的。当我重新启动应用程序,读者获取第一个计数任何插入之前确定。

In this simple example I have 2 Thread objects, one for writing and second one for reading. The reader Thread gets count of written objects always as 0, but inside writer scope the size() for items in DB is correct. When I relaunch app, the reader gets the first count ok before any insertions.

Thread writer = new Thread() {

    @Override
    public void run() {
        while (mRunning) {
            try {
                Realm r = Realm.getInstance(context, "test_db");
                r.beginTransaction();

                TestData data = r.createObject(TestData.class);

                r.commitTransaction();

                Logger.e("WRITER THREAD COUNT: " + 
                    r.where(TestData.class).findAll().size());

                sleep(LATENCY);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};

writer.setPriority(Thread.MAX_PRIORITY);
writer.start();

Thread reader = new Thread() {

    @Override
    public void run() {
        while (mRunning) {
            try {
                Logger.e("READING THREAD COUNT: " + Realm.getInstance(context,
                        "test_db").where(TestData.class).findAll().size());

                sleep(LATENCY);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};

reader.setPriority(Thread.MAX_PRIORITY);
reader.start();

有没有需要做的事情这个工作?

Is there something needed to do for this to work?

感谢。

推荐答案

从埃马努埃莱这里境界

你所描述的是预期的行为:)由于读线程不具有尺蠖,它没有办法从读线程接收通知,绝不会更新,除非你手动执行刷新

What you are describing is expected behavior :) Since the reader thread doesn't have a Looper, it has no way to receive notifications from the reader thread and will never update unless you manually execute a refresh.

在了回购,我们有几个例子使用线程使用和不使用尺蠖,说明当前的最佳做法。

In out repo we have several examples (not to mention unit tests) using threads with and without Looper, illustrating the current best practices.

这篇关于编写和线程之间的阅读与Android境界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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