简体   繁体   English

带有线程的Android中介模式

[英]Android mediator pattern with threads

I got the following problem: 我遇到以下问题:

I want to use the mediator pattern for an app. 我想为应用程序使用中介模式。

I got a producer that creates values. 我有一个创造价值的生产者。 I got a mediator that stores the values in a queue(which is private, so getters and setters exist) and notifices the consumer that there are new values in the queue. 我得到了一个将值存储在队列中的介体(这是私有的,因此存在getter和setter),并通知消费者队列中有新值。 I got the consumer, that gets notified about a new value, gets it and does stuff with it... 我得到了消费者,得到了有关新值的通知,得到了它并对其进行了处理...

I want all 3 classes to run on own threads. 我希望所有3个类都在自己的线程上运行。 But I also want to be efficient. 但是我也想提高效率。

If I understand it right, my mediator thread will be GCed when run() ends... so I would need to keep it alive by a loop, don't I? 如果我理解正确的话,我的介体线程将在run()结束时被GC ...因此,我需要通过循环使其保持活动状态,不是吗? Like while(true), but this is not very efficient. 就像while(true)一样,但这不是很有效。 Is there a better way? 有没有更好的办法? Or am I totally incorrect and the mediator wouldn't be GCed? 还是我完全不正确,调解员不会被GC?

Thanks in advance 提前致谢

You're right that once your mediator object's run() method returns, the thread will terminate. 没错,一旦中介者对象的run()方法返回,线程将终止。 But that doesn't mean that the mediator will be GCed; 但这并不意味着调解员将被GC化; if there is a live reference to your mediator object, it won't be. 如果存在对您的调解器对象的实时引用,则不会。 However, if the thread has exited, the mediator won't be particularly useful. 但是,如果线程退出,则调解器将不是特别有用。 A while(true) loop is one way to deal with this. while(true)循环是处理此问题的一种方法。 A while(true) loop is not necessarily inefficient. while(true)循环不一定效率低下。 It could easily work by calling wait() on some object until new stuff appears in the queue. 通过在某个对象上调用wait()直到队列中出现新内容,可以很容易地工作。 The thread will be in a wait state and will not consume cpu resources. 该线程将处于等待状态,并且不会消耗cpu资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM