I am writing a class that pauses operations from other methods in ConcurrentLinkedQueue, and then has a process () method that should only be called from the creating thread that processes the queue. This is due to the fact that operations from other methods can be called from other threads, but their actual actions should be performed only in the thread of the creator. This is similar to Android runOnUiThread , which should be used to run any user interface code outside of the user interface thread.
My idea of a process method is to first state that the creator thread calls it, and then just start every thing in the queue. I'm not sure how to compare the current thread with a stored reference to Thread; I cannot find documentation on whether links are guaranteed to be the same. Should I use the equals method? Should I just use the == operator? Is it possible to compare Thread objects, or should I compare their names or some other data?
The corresponding bit of code will look something like this: (queue logic not shown)
public class MultiThreadTasker { private Thread creatorThread; public MultiThreadTasker() { creatorThread = Thread.currentThread(); } public void process() { if(Thread.currentThread() != creatorThread) { throw new IllegalArgumentException("..."); }
Recommendations regarding alternative ways to do this will also be welcome. It seems that I am inventing Executor, but I have not seen any Executor that allows you to manually run tasks instead of processing your own threads.
source share