简体   繁体   中英

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. 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. 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? Like while(true), but this is not very efficient. Is there a better way? Or am I totally incorrect and the mediator wouldn't be GCed?

Thanks in advance

You're right that once your mediator object's run() method returns, the thread will terminate. But that doesn't mean that the mediator will be GCed; 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. A while(true) loop is not necessarily inefficient. It could easily work by calling wait() on some object until new stuff appears in the queue. The thread will be in a wait state and will not consume cpu resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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