How to compare Thread.currentThread () with a saved thread reference? ==, equal to ..?

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.

+4
source share
2 answers

If you want tasks to run in the current thread, why do they even share the queue? I would have a local queue for each thread that only this thread can see / use.

This is what I would do.

 private static final ThreadLocal<Queue<Runnable>> QUEUE = new ThreadLocal<Queue<Runnable>>() { @Override protected Queue<Runnable> initialValue() { return new LinkedList<Runnable>(); } }; public static void runLater(Runnable runnable) { QUEUE.get().add(runnable); } public static void runAll() { for (Runnable runnable : QUEUE.get()) runnable.run(); QUEUE.get().clear(); } 
+1
source

If comparing themes does not work, you can use the local UUID thread (http://docs.oracle.com/javase/6/docs/api/java/lang/ThreadLocal.html, http://docs.oracle.com/ javase / 1.5.0 / docs / api / java / util / UUID.html ) for comparing invokers. You must fill in the local stream field in the constructor.

0
source

Source: https://habr.com/ru/post/1433371/


All Articles