Skip to content Skip to sidebar Skip to footer

How To Ensure Synchronization When One Thread Keeps Sending Data To Another Thread?

There are 2 threads: Thread1 and Thread2, in addition to the main UI thread. The UI thread spawns Thread1. Thread1 spwans Thread2 and keeps sending an array to Thread2 at periodic

Solution 1:

I don't know if you need a good performance but one simple way to achieve is to use this object https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html

Solution 2:

Assuming Thread1 and Thread2 are a both HandlerThreads, they can can just send messages to each other using each other's Handler(s).

I started off using handlers but did not know how to send Thread2's handler to Thread1, so that Thread1 can keep posting data to Thread2's message queue.

Specific to this question, you can either create a method on HandlerThread2 that wraps the handler.post() and call that from HandlerThread1's reference to HandlerThread2.

//in HandlerThread2publicvoidsend(SomeData data) {
    this.handler.post([runnable]);
}

Or you can provide an accessor in HandlerThread2 to get the actual handler from HandlerThread2 and use it directly.

//in HandlerThread2public Handler getHandler() {
    returnthis.handler;
}

Post a Comment for "How To Ensure Synchronization When One Thread Keeps Sending Data To Another Thread?"